# 日期时间算术运算

### 为日期时间数组加上或减去一定的持续时间

`t1 = datetime('now')`
```t1 = datetime 25-Jan-2024 22:15:28 ```

`t2 = t1 + hours(1:3)`
```t2 = 1x3 datetime 25-Jan-2024 23:15:28 26-Jan-2024 00:15:28 26-Jan-2024 01:15:28 ```

`dt = diff(t2)`
```dt = 1x2 duration 01:00:00 01:00:00 ```

`diff` 返回由小时数、分钟数和秒数构成的精确持续时间。

`t2 = t1 - minutes(20:10:40)`
```t2 = 1x3 datetime 25-Jan-2024 21:55:28 25-Jan-2024 21:45:28 25-Jan-2024 21:35:28 ```

`t2 = t1 + [1:3]`
```t2 = 1x3 datetime 26-Jan-2024 22:15:28 27-Jan-2024 22:15:28 28-Jan-2024 22:15:28 ```

### 包含时区的日期时间值加法

`t1 = datetime(2014,3,8,0,0,0,'TimeZone','America/New_York')`
```t1 = datetime 08-Mar-2014 ```

`t2 = t1 + days(0:2)`
```t2 = 1x3 datetime 08-Mar-2014 00:00:00 09-Mar-2014 00:00:00 10-Mar-2014 01:00:00 ```

`dt = diff(t2)`
```dt = 1x2 duration 24:00:00 24:00:00 ```

`t3 = t1 + caldays(0:2)`
```t3 = 1x3 datetime 08-Mar-2014 09-Mar-2014 10-Mar-2014 ```

`dt = diff(t3)`
```dt = 1x2 duration 24:00:00 23:00:00 ```

### 将日历持续时间与日期时间数组相加

`t1 = datetime(2014,1,31)`
```t1 = datetime 31-Jan-2014 ```
`t2 = t1 + calmonths(1:4)`
```t2 = 1x4 datetime 28-Feb-2014 31-Mar-2014 30-Apr-2014 31-May-2014 ```

`t2` 中的每个日期时间都出现在每个月的最后一天。

`dt = caldiff(t2,'days')`
```dt = 1x3 calendarDuration 31d 30d 31d ```

`dt` 中连续的日期时间值对之间相差的天数并非始终相同，这是因为不同的月份由不同的天数组成。

`t2 = t1 + calyears(0:4)`
```t2 = 1x5 datetime 31-Jan-2014 31-Jan-2015 31-Jan-2016 31-Jan-2017 31-Jan-2018 ```

`dt = caldiff(t2,'days')`
```dt = 1x4 calendarDuration 365d 365d 366d 365d ```

`dt` 中连续的日期时间值对之间相差天数并非始终相同，这是因为 2016 年是闰年，有 366 天。

`t2 = datetime(2014,1,31) + calmonths(3) + caldays(30)`
```t2 = datetime 30-May-2014 ```

`t2 = datetime(2014,1,31) + caldays(30) + calmonths(3)`
```t2 = datetime 02-Jun-2014 ```

### 日历持续时间算术运算

`d1 = calyears(1) + calmonths(2) + caldays(20)`
```d1 = calendarDuration 1y 2mo 20d ```
`d2 = calmonths(11) + caldays(23)`
```d2 = calendarDuration 11mo 23d ```
`d = d1 + d2`
```d = calendarDuration 2y 1mo 43d ```

`2*d`
```ans = calendarDuration 4y 2mo 86d ```

### 以精确单位计算流逝时间

`t2 = datetime('now') + caldays(1:3)`
```t2 = 1x3 datetime 26-Jan-2024 22:15:30 27-Jan-2024 22:15:30 28-Jan-2024 22:15:30 ```
`t1 = datetime('yesterday')`
```t1 = datetime 24-Jan-2024 ```
`dt = t2 - t1`
```dt = 1x3 duration 70:15:30 94:15:30 118:15:30 ```
`whos dt`
``` Name Size Bytes Class Attributes dt 1x3 40 duration ```

`dt` 以“时:分:秒”的格式存储持续时间。

`dt.Format = 'd'`
```dt = 1x3 duration 2.9274 days 3.9274 days 4.9274 days ```

`dt2 = 1.2*dt`
```dt2 = 1x3 duration 3.5129 days 4.7129 days 5.9129 days ```

### 以日历单位计算流逝时间

`t1 = datetime('today')`
```t1 = datetime 25-Jan-2024 ```
`t2 = t1 + calmonths(0:2) + caldays(4)`
```t2 = 1x3 datetime 29-Jan-2024 29-Feb-2024 29-Mar-2024 ```
`dt = between(t1,t2)`
```dt = 1x3 calendarDuration 4d 1mo 4d 2mo 4d ```