%% Set Times of Day for Datetimes
% Set the times of day in a datetime array according to the times of day in another datetime array. There are two ways to set the times of day. Only the second method is correct across Daylight Saving Time (DST) shifts.
% Create a datetime array. Each element has a different time component.

t1 = datetime(2015,3,7) + hours(1:4)

%
% Create a second datetime array. Each element has the same date and time components.

t2 = datetime(2015,3,[8 8 8 8])

%
% Set the times of day in t2 according to the times of day in t1.

t2 = dateshift(t2,'start','day') + timeofday(t1)

%
% Create a datetime array with elements that have the TimeZone property set to 'America/New_York'.

tz = 'America/New_York';
fmt = 'dd-MMM-yyyy HH:mm:ss z';
t3 = datetime(2015,3,8,'TimeZone',tz,'Format',fmt) + hours(1:4)

%
% Calculate the elapsed time since midnight. timeofday accounts for the DST shift that occurred on March 8, 2015.

d = timeofday(t3)

%
% Set the times of day in t4 according to times of day in t1. To set the times of day correctly regardless of the time zone or the day of year, use the Hour, Minute, and Second properties of t1.

t4 = datetime(2015,3,[8 8 8 8],'TimeZone',tz,'Format',fmt);
t4.Hour = t1.Hour;
t4.Minute = t1.Minute;
t4.Second = t1.Second;
t4

% In this time zone 2:00 a.m. Eastern Standard Time did not exist on March 8, 2015, because the DST shift occurred then. The second element of the result has a time component of 3:00 a.m. Eastern Daylight Time.
% Copyright 2015 The MathWorks, Inc.