> ## Documentation Index
> Fetch the complete documentation index at: https://help.dingtalk.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Pre-Calculate Durations

> Call this API to pre-calculate an employee's overtime, business trip, and leave durations by calendar or working day in a set unit.

Call this API to pre-calculate an employee's overtime, business trip, and leave durations based on scheduling in the attendance system.

## API Call Description

For example, an employee is scheduled to work on November 2 (start time 09:00, end time 18:00) and has a day off on November 3.

The employee plans to take leave from 09:00:00 on November 2 to 18:00:00 on November 3. Call this API to get the expected leave duration within this range. The result is only one day.

* If an employee is not in an attendance group or has no shift scheduled on the leave date, the leave duration is calculated based on the default attendance time.
* Configure the default attendance time at **DingTalk mobile > Workbench > Attendance > Settings > More Settings > Leave and Attendance Approval > Default Attendance Time**. For example:

  An employee is scheduled to work on November 2 (start time 09:00, end time 18:00) and has no shift scheduled on November 3. The default shift is 08:30–17:30. The employee plans to take leave from 09:00:00 on November 2 to 18:00:00 on November 3. Call this API to get the expected leave duration within this range. The result is 2 days.

## Request

### Basic Information

| Field | Value |
| - | - |
| HTTP URL | [https://api.dingtalk.io/v1.0/attendance/approvals/durations/calculate](https://api.dingtalk.io/v1.0/attendance/approvals/durations/calculate) |
| HTTP Method | POST |
| Supported app types | appType-Internal app　appType-Third-party enterprise app |
| Required permissions | permission-qyapi\_attendance\_group\_read-Attendance group query permission |

### Request Header

| Name | Type | Required | Description |
| - | - | - | - |
| x-acs-dingtalk-access-token | String | Yes | The access credential for calling this API. Obtain it as follows:   - Internal app: call the [Get the access token of an internal app](https://help.dingtalk.io/open/development/obtain-the-access-token-of-an-internal-app.md) API. - Third-party enterprise app: call the API for getting the access token of an organization that has authorized the third-party app. |

### Query Parameters

| Name | Type | Required | Description |
| - | - | - | - |
| userId | String | No | The userId of the user. |

### Request Body

| Name | Type | Required | Description |
| - | - | - | - |
| bizType | Long | No | Approval form type:   - 1: Overtime - 2: Business trip - 3: Leave |
| fromTime | String | No | Start time. The start time cannot be more than 31 days before the current time. Supported formats:   - 2019-08-15 - 2019-08-15 AM - 2019-08-15 12:43 |
| toTime | String | No | End time.   - When biz\_type is 1, the end time minus the start time cannot exceed 1 day. - When biz\_type is 2 or 3, the number of days between the start time and the end time cannot exceed 31.   Supported formats:   - 2019-08-15 - 2019-08-15 AM - 2019-08-15 12:43 |
| durationUnit | String | No | Duration unit. Supported values:   - day - halfDay - hour: When biz\_type is 1, only hour is supported.   The time format must match the duration unit:   - 2019-08-15 corresponds to day - 2019-08-15 AM corresponds to halfDay - 2019-08-15 12:43 corresponds to hour |
| calculateModel | Long | No | Calculation method:   - 0: By calendar day - 1: By working day |
| leaveCode | String | No | Unique identifier of the leave rules. Optional. Applies only when bizType=3 (leave). If specified, the duration is rounded according to the rounding rule configured for the leave type. |

### Request Example

HTTP

```http theme={"theme":{"light":"github-light","dark":"github-dark"}}
POST /v1.0/attendance/approvals/durations/calculate?userId=manager123 HTTP/1.1
Host:api.dingtalk.io
x-acs-dingtalk-access-token:234sad32qr4q32xxx
Content-Type:application/json

{
  "bizType" : 3,
  "fromTime" : "2019-08-15",
  "toTime" : "2019-08-15",
  "durationUnit" : "day",
  "calculateModel" : 1,
  "leaveCode" : "e2dsad-34dfa-2vas23da"
}
```

Java

```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
// This file is auto-generated, don't edit it. Thanks.
package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    /**
     * Initialize the account Client with a Token
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkattendance_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkattendance_1_0.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.dingtalkattendance_1_0.Client client = Sample.createClient();
        com.aliyun.dingtalkattendance_1_0.models.CalculateDurationHeaders calculateDurationHeaders = new com.aliyun.dingtalkattendance_1_0.models.CalculateDurationHeaders();
        calculateDurationHeaders.xAcsDingtalkAccessToken = "<your access token>";
        com.aliyun.dingtalkattendance_1_0.models.CalculateDurationRequest calculateDurationRequest = new com.aliyun.dingtalkattendance_1_0.models.CalculateDurationRequest()
                .setUserId("manager123")
                .setBizType(3L)
                .setFromTime("2019-08-15")
                .setToTime("2019-08-15")
                .setDurationUnit("day")
                .setCalculateModel(1L)
                .setLeaveCode("e2dsad-34dfa-2vas23da");
        try {
            client.calculateDurationWithOptions(calculateDurationRequest, calculateDurationHeaders, new com.aliyun.teautil.models.RuntimeOptions());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err contains the code and message attributes, which help locate the issue
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err contains the code and message attributes, which help locate the issue
            }

        }        
    }
}
```

Python

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import os
import sys

from typing import List

from alibabacloud_dingtalk.attendance_1_0.client import Client as dingtalkattendance_1_0Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dingtalk.attendance_1_0 import models as dingtalkattendance__1__0_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient

class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> dingtalkattendance_1_0Client:
        """
        Initialize the account Client with a Token
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config()
        config.protocol = 'https'
        config.region_id = 'central'
        return dingtalkattendance_1_0Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        calculate_duration_headers = dingtalkattendance__1__0_models.CalculateDurationHeaders()
        calculate_duration_headers.x_acs_dingtalk_access_token = '<your access token>'
        calculate_duration_request = dingtalkattendance__1__0_models.CalculateDurationRequest(
            user_id='manager123',
            biz_type=3,
            from_time='2019-08-15',
            to_time='2019-08-15',
            duration_unit='day',
            calculate_model=1,
            leave_code='e2dsad-34dfa-2vas23da'
        )
        try:
            client.calculate_duration_with_options(calculate_duration_request, calculate_duration_headers, util_models.RuntimeOptions())
        except Exception as err:
            if not UtilClient.empty(err.code) and not UtilClient.empty(err.message):
                # err contains the code and message attributes, which help locate the issue
                pass

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        calculate_duration_headers = dingtalkattendance__1__0_models.CalculateDurationHeaders()
        calculate_duration_headers.x_acs_dingtalk_access_token = '<your access token>'
        calculate_duration_request = dingtalkattendance__1__0_models.CalculateDurationRequest(
            user_id='manager123',
            biz_type=3,
            from_time='2019-08-15',
            to_time='2019-08-15',
            duration_unit='day',
            calculate_model=1,
            leave_code='e2dsad-34dfa-2vas23da'
        )
        try:
            await client.calculate_duration_with_options_async(calculate_duration_request, calculate_duration_headers, util_models.RuntimeOptions())
        except Exception as err:
            if not UtilClient.empty(err.code) and not UtilClient.empty(err.message):
                # err contains the code and message attributes, which help locate the issue
                pass

if __name__ == '__main__':
    Sample.main(sys.argv[1:])
```

PHP

```php theme={"theme":{"light":"github-light","dark":"github-dark"}}
<?php

// This file is auto-generated, don't edit it. Thanks.
namespace AlibabaCloud\SDK\Sample;

use AlibabaCloud\SDK\Dingtalk\Vattendance_1_0\Dingtalk;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dingtalk\Vattendance_1_0\Models\CalculateDurationHeaders;
use AlibabaCloud\SDK\Dingtalk\Vattendance_1_0\Models\CalculateDurationRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class Sample {

    /**
     * Initialize the account Client with a Token
     * @return Dingtalk Client
     */
    public static function createClient(){
        $config = new Config([]);
        $config->protocol = "https";
        $config->regionId = "central";
        return new Dingtalk($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        $client = self::createClient();
        $calculateDurationHeaders = new CalculateDurationHeaders([]);
        $calculateDurationHeaders->xAcsDingtalkAccessToken = "<your access token>";
        $calculateDurationRequest = new CalculateDurationRequest([
            "userId" => "manager123",
            "bizType" => 3,
            "fromTime" => "2019-08-15",
            "toTime" => "2019-08-15",
            "durationUnit" => "day",
            "calculateModel" => 1,
            "leaveCode" => "e2dsad-34dfa-2vas23da"
        ]);
        try {
            $client->calculateDurationWithOptions($calculateDurationRequest, $calculateDurationHeaders, new RuntimeOptions([]));
        }
        catch (Exception $err) {
            if (!($err instanceof TeaError)) {
                $err = new TeaError([], $err->getMessage(), $err->getCode(), $err);
            }
            if (!Utils::empty_($err->code) && !Utils::empty_($err->message)) {
                // err contains the code and message attributes, which help locate the issue
            }
        }
    }
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
Sample::main(array_slice($argv, 1));
```

Go

```go theme={"theme":{"light":"github-light","dark":"github-dark"}}
// This file is auto-generated, don't edit it. Thanks.
package main

import (
  "os"
  util  "github.com/alibabacloud-go/tea-utils/v2/service"
  dingtalkattendance_1_0  "github.com/alibabacloud-go/dingtalk/attendance_1_0"
  openapi  "github.com/alibabacloud-go/darabonba-openapi/v2/client"
  "github.com/alibabacloud-go/tea/tea"
)

/**
 * Initialize the account Client with a Token
 * @return Client
 * @throws Exception
 */
func CreateClient () (_result *dingtalkattendance_1_0.Client, _err error) {
  config := &openapi.Config{}
  config.Protocol = tea.String("https")
  config.RegionId = tea.String("central")
  _result = &dingtalkattendance_1_0.Client{}
  _result, _err = dingtalkattendance_1_0.NewClient(config)
  return _result, _err
}

func _main (args []*string) (_err error) {
  client, _err := CreateClient()
  if _err != nil {
    return _err
  }

  calculateDurationHeaders := &dingtalkattendance_1_0.CalculateDurationHeaders{}
  calculateDurationHeaders.XAcsDingtalkAccessToken = tea.String("<your access token>")
  calculateDurationRequest := &dingtalkattendance_1_0.CalculateDurationRequest{
    UserId: tea.String("manager123"),
    BizType: tea.Int64(3),
    FromTime: tea.String("2019-08-15"),
    ToTime: tea.String("2019-08-15"),
    DurationUnit: tea.String("day"),
    CalculateModel: tea.Int64(1),
    LeaveCode: tea.String("e2dsad-34dfa-2vas23da"),
  }
  tryErr := func()(_e error) {
    defer func() {
      if r := tea.Recover(recover()); r != nil {
        _e = r
      }
    }()
    _, _err = client.CalculateDurationWithOptions(calculateDurationRequest, calculateDurationHeaders, &util.RuntimeOptions{})
    if _err != nil {
      return _err
    }

    return nil
  }()

  if tryErr != nil {
    var err = &tea.SDKError{}
    if _t, ok := tryErr.(*tea.SDKError); ok {
      err = _t
    } else {
      err.Message = tea.String(tryErr.Error())
    }
    if !tea.BoolValue(util.Empty(err.Code)) && !tea.BoolValue(util.Empty(err.Message)) {
      // err contains the code and message attributes, which help locate the issue
    }

  }
  return _err
}

func main() {
  err := _main(tea.StringSlice(os.Args[1:]))
  if err != nil {
    panic(err)
  }
}
```

Node.js

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
// This file is auto-generated, don't edit it
import Util, * as $Util from '@alicloud/tea-util';
import dingtalkattendance_1_0, * as $dingtalkattendance_1_0 from '@alicloud/dingtalk/attendance_1_0';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import * as $tea from '@alicloud/tea-typescript';

export default class Client {

  /**
   * Initialize the account Client with a Token
   * @return Client
   * @throws Exception
   */
  static createClient(): dingtalkattendance_1_0 {
    let config = new $OpenApi.Config({ });
    config.protocol = "https";
    config.regionId = "central";
    return new dingtalkattendance_1_0(config);
  }

  static async main(args: string[]): Promise<void> {
    let client = Client.createClient();
    let calculateDurationHeaders = new $dingtalkattendance_1_0.CalculateDurationHeaders({ });
    calculateDurationHeaders.xAcsDingtalkAccessToken = "<your access token>";
    let calculateDurationRequest = new $dingtalkattendance_1_0.CalculateDurationRequest({
      userId: "manager123",
      bizType: 3,
      fromTime: "2019-08-15",
      toTime: "2019-08-15",
      durationUnit: "day",
      calculateModel: 1,
      leaveCode: "e2dsad-34dfa-2vas23da",
    });
    try {
      await client.calculateDurationWithOptions(calculateDurationRequest, calculateDurationHeaders, new $Util.RuntimeOptions({ }));
    } catch (err) {
      if (!Util.empty(err.code) && !Util.empty(err.message)) {
        // err contains the code and message attributes, which help locate the issue
      }

    }    
  }

}

Client.main(process.argv.slice(2));
```

C#

```csharp theme={"theme":{"light":"github-light","dark":"github-dark"}}
// This file is auto-generated, don't edit it. Thanks.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

using Tea;
using Tea.Utils;

namespace AlibabaCloud.SDK.Sample
{
    public class Sample 
    {

        /**
         * Initialize the account Client with a Token
         * @return Client
         * @throws Exception
         */
        public static AlibabaCloud.SDK.Dingtalkattendance_1_0.Client CreateClient()
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config();
            config.Protocol = "https";
            config.RegionId = "central";
            return new AlibabaCloud.SDK.Dingtalkattendance_1_0.Client(config);
        }

        public static void Main(string[] args)
        {
            AlibabaCloud.SDK.Dingtalkattendance_1_0.Client client = CreateClient();
            AlibabaCloud.SDK.Dingtalkattendance_1_0.Models.CalculateDurationHeaders calculateDurationHeaders = new AlibabaCloud.SDK.Dingtalkattendance_1_0.Models.CalculateDurationHeaders();
            calculateDurationHeaders.XAcsDingtalkAccessToken = "<your access token>";
            AlibabaCloud.SDK.Dingtalkattendance_1_0.Models.CalculateDurationRequest calculateDurationRequest = new AlibabaCloud.SDK.Dingtalkattendance_1_0.Models.CalculateDurationRequest
            {
                UserId = "manager123",
                BizType = 3,
                FromTime = "2019-08-15",
                ToTime = "2019-08-15",
                DurationUnit = "day",
                CalculateModel = 1,
                LeaveCode = "e2dsad-34dfa-2vas23da",
            };
            try
            {
                client.CalculateDurationWithOptions(calculateDurationRequest, calculateDurationHeaders, new AlibabaCloud.TeaUtil.Models.RuntimeOptions());
            }
            catch (TeaException err)
            {
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err contains the code and message attributes, which help locate the issue
                }
            }
            catch (Exception _err)
            {
                TeaException err = new TeaException(new Dictionary<string, object>
                {
                    { "message", _err.Message }
                });
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err contains the code and message attributes, which help locate the issue
                }
            }
        }

    }
}
```

## Response

### Response Body

| Name | Type | Description |
| - | - | - |
| result | Object | The returned result. |
| duration | double | Total duration. The unit of this field matches the unit configured for the corresponding approval form in your organization. |
| durationDetail | Array | Details. |
| date | String | Date. |
| duration | double | Daily duration. The unit of this field matches the unit configured for the corresponding approval form in your organization. |
| success | Boolean | Whether the API call succeeded. |

### Response Body Example

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
HTTP/1.1 200 OK
Content-Type:application/json

{
  "result" : {
    "duration" : 2,
    "durationDetail" : [ {
      "date" : "2019-08-15",
      "duration" : 1.6
    } ]
  },
  "success" : true
}
```

### Error Codes

If the API call returns an error, find the solution in the [Global Error Codes](https://help.dingtalk.io/open/development/server-api-error-codes-1.md) document based on the error message.

| HttpCode | Error Code | Error Message | Description |
| - | - | - | - |
| 400 | illegalCalculateType | Invalid duration calculation mode | Invalid duration calculation mode |
| 400 | illegalDurationUnit | Invalid duration unit | Invalid duration unit |
| 400 | illegalApproveType | Invalid approval type | Invalid approval type |
| 400 | invalidRequestParams | Parameter error (check the parameters against the documentation) | Parameter error (check the parameters against the documentation) |
| 400 | illegalOvertimeDurationUnit | Invalid overtime duration unit (overtime supports hours only) | Invalid overtime duration unit (overtime supports hours only) |
| 400 | illegalDateTypeForHalfDay | Invalid start/end time format when DURATION\_UNIT is half day | Invalid start/end time format when DURATION\_UNIT is half day |
| 400 | beginDateCannotAfterEndDate | The start time cannot be later than the end time | The start time cannot be later than the end time |
| 400 | durationTooLong | The time span between the start and end times is too long | The time span between the start and end times is too long |
| 400 | dateTooEarly | The time cannot be earlier than the specified number of days | The time cannot be earlier than the specified number of days |
| 400 | overtimeDurationTooLong | The overtime duration is too long | The overtime duration is too long |
| 400 | systemError | System error | System error |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.