# calmonths

Calendar duration in months

## Syntax

``M = calmonths(X)``

## Description

The `calmonths` function returns an array that represents calendar months. When you use arrays that have the `calendarDuration` data type in calendar calculations, the calculations take into account leap years, Daylight Saving Time shifts, and the differing lengths of calendar months. For calculations that involve fixed lengths of time, use the `duration` data type.

````M = calmonths(X)` returns an array representing calendar months equivalent to the values in `X`. If `X` is a numeric array, then `M` is a `calendarDuration` array with each element equal to the number of calendar months in the corresponding element of `X`.If `X` is a `calendarDuration` array, then `M` is a `double` array with each element equal to the number of whole calendar months in the corresponding element of `X`. ```

example

## Examples

collapse all

```X = magic(4); M = calmonths(X)```
```M = 4x4 calendarDuration 1y 4mo 2mo 3mo 1y 1mo 5mo 11mo 10mo 8mo 9mo 7mo 6mo 1y 4mo 1y 2mo 1y 3mo 1mo ```

Create a `datetime` value whose date component is the end of January.

`D = datetime('2021-01-31')`
```D = datetime 31-Jan-2021 ```

Add an array of calendar months to `D` by using the `calmonths` function. Since February has fewer days than January, it is unambiguous that adding a calendar month to January 31st results in a date of February 28th (since 2021 is not a leap year).

`D = D + calmonths(0:2)`
```D = 1x3 datetime 31-Jan-2021 28-Feb-2021 31-Mar-2021 ```

Now create a `datetime` value whose date component is the end of February.

`D2 = datetime('2021-02-28')`
```D2 = datetime 28-Feb-2021 ```

Calendar months have differing lengths. However, March and April have more days than February. So adding calendar months to February 28th results in dates of March 28th and April 28th.

`D2 = D2 + calmonths(0:2)`
```D2 = 1x3 datetime 28-Feb-2021 28-Mar-2021 28-Apr-2021 ```

To ensure that `D2` has end-of-month values, use the `dateshift` function.

`D2 = dateshift(D2,'end','month')`
```D2 = 1x3 datetime 28-Feb-2021 31-Mar-2021 30-Apr-2021 ```

Create an array of calendar durations. Then, convert each value to the equivalent number of whole calendar months.

`X = calmonths(15:17) + caldays(8) + hours(1.2345)`
```X = 1x3 calendarDuration 1y 3mo 8d 1h 14m 4.2s 1y 4mo 8d 1h 14m 4.2s 1y 5mo 8d 1h 14m 4.2s ```
`M = calmonths(X)`
```M = 1×3 15 16 17 ```

## Input Arguments

collapse all

Input array, specified as a numeric array, calendar duration array, or logical array. If `X` is a numeric array, it must contain only integer values. That is, you cannot create fractional calendar units.

## Version History

Introduced in R2014b