%% Add Calendar Months to Ends of Months
% Create a datetime value whose date component is the end of January.

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

% 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)

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

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

% 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)

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

D2 = dateshift(D2,'end','month')

% Copyright 2020 The MathWorks, Inc.