%% Set Times of Day for datetime Arrays
% 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.
% Split the time portions from the first datetime array by using timeofday and add the time portions to the second datetime array.
% Set the Hour, Minute, and Second components of the second datetime array equal to the Hour, Minute, and Second components of the first datetime array.
% If you use the first way, you might not always account for Daylight Saving Time (DST) shifts correctly. Only the second way is always correct across any DST shifts.
% Create a datetime array. Each element has a different time component.

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

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

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

%
% Set the times of day in DT2 according to the times of day in DT1. Because DT1 and DT2 do not have time zones their time components are identical.

DT2 = dateshift(DT2,'start','day') + timeofday(DT1)

%
% Create a datetime array with elements that have the TimeZone property set to 'America/New_York'. Because DT3 has a time zone and a DST shift that occurs on March 8, 2015, the time components of DT3 are not the same as those of DT1.

tz = 'America/New_York';
fmt = 'dd-MMM-yyyy HH:mm:ss z';
DT3 = datetime(2015,3,8,'TimeZone',tz,'Format',fmt) + timeofday(DT1)

%
% Display the elapsed times since midnight. timeofday accounts for the DST shift. The elapsed times show that the times in DT3 are incorrect. The last time in DT3 corresponds to 5:00 a.m. But in DT1 only four hours elapsed since midnight.

T = timeofday(DT3)

%
% To set the times of day of DT4 correctly regardless of the time zone or the day of year, use the Hour, Minute, and Second properties of DT1.

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

% 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-2021 The MathWorks, Inc.