%% Sequence of Datetime Values Using Calendar Rules
% This example shows how to use the dateshift function to generate sequences of dates and time where each instance obeys a rule relating to a calendar unit or a unit of time. For instance, each datetime must occur at the beginning a month, on a particular day of the week, or at the end of a minute. The resulting datetime values in the sequence are not necessarily equally spaced.
%% Dates on Specific Day of Week
% Generate a sequence of dates consisting of the next three occurrences of Monday. First, define today's date.

t1 = datetime('today','Format','dd-MMM-yyyy eee')

%
% The first input to dateshift is always the datetime array from which you want to generate a sequence. Specify 'dayofweek' as the second input to indicate that the datetime values in the output sequence must fall on a specific day of the week. You can specify the day of the week either by number or by name. For example, you can specify Monday either as 2 or 'Monday'.

t = dateshift(t1,'dayofweek',2,1:3)

%
%% Dates at Start of Month
% Generate a sequence of start-of-month dates beginning with April 1, 2014. Specify 'start' as the second input to dateshift to indicate that all datetime values in the output sequence should fall at the start of a particular unit of time. The third input argument defines the unit of time, in this case, month. The last input to dateshift can be an array of integer values that specifies how t1 should be shifted. In this case, 0 corresponds to the start of the current month, and 4 corresponds to the start of the fourth month from t1.

t1 = datetime(2014,04,01);
t = dateshift(t1,'start','month',0:4)

%
%% Dates at End of Month
% Generate a sequence of end-of-month dates beginning with April 1, 2014.

t1 = datetime(2014,04,01);
t = dateshift(t1,'end','month',0:2)

%
% Determine the number of days between each date.

dt = caldiff(t,'days')

% The dates are not equally spaced.
%
%% Other Units of Dates and Time
% You can specify other units of time such as week, day, and hour.

t1 = datetime('now')

%

t = dateshift(t1,'start','hour',0:4)

%
%% Previous Occurrences of Dates and Time
% Generate a sequence of datetime values beginning with the previous hour. Negative integers in the last input to dateshift correspond to datetime values earlier than t1.

t = dateshift(t1,'start','hour',-1:1)

% Copyright 2012 The MathWorks, Inc.