Calendar duration in months
M = calmonths( returns
an array representing calendar months equivalent to the values in
X is a numeric array, then
calendarDuration array with each element equal
to the number of calendar months in the corresponding element of
X is a
M is a
double array with
each element equal to the number of whole calendar months in the corresponding
calmonths function creates months that can account for the
differing lengths of calendar months when used in calendar calculations.
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
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
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
This function fully supports tall arrays. For more information, see Tall Arrays.
This function fully supports distributed arrays. For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox).