MATLAB: How to subtract ‘datetime’ from ‘datetime’ in MATLAB GUI

data convertiondatestrdatetimeguideMATLABmatlab guitime seriestime zone

Hi, I am designing a program to calculate the time different between two cities.
The operation is: subtracting second city time from the first one. I used the bellow code to get the cities time and convert it into 'string':
city1 = datestr(datetime('now','TimeZone','local',...
'Format','dd-MM-yyyy HH:mm:ss Z'));
city1.TimeZone = 'America/New_York';
city2 = datestr(datetime('now','TimeZone','local',...
'Format','dd-MM-yyyy HH:mm:ss Z'));
city2.TimeZone = 'Africa/Khartoum';
The output will be in a formatted string as:
city1 =
'25-Aug-2018 19:34:29'
city2 =
'25-Aug-2018 13:34:29'
The above is working properly but I can not subtract them in this form.
My question is: How to subtract the string forms above and get 4 cells output as "06:00" ?

Best Answer

The problem is converting to strings instead of just comparing...
What will work to compute the offset including DST if in effect is--
v=now; % return the local current time as datenum(*)
t1=datetime(v,'ConvertFrom','datenum','TimeZone','America/New_York','Format','d-MMM-y HH:mm:ss Z');
t2=datetime(v,'ConvertFrom','datenum','TimeZone','Africa/Khartoum','Format','d-MMM-y HH:mm:ss Z');
u=t2-t1
u =
duration
-7:00:00
The above sets the local time a variable before calling the conversion factors to ensure there isn't a rollover between the two calls to datetime that would introduce a small error in the result if were to occur.
(*) Interesting shortcoming that TMW hasn't introduced a datetime-aware routine to parallel the old standby that returns a datenum.
ADDENDUM
An alternative would be to use the timezones table data--
A=timezones('Africa'); % get the Africa table
N=timezones('America'); % and Americas, too
Z1=N(contains(N.Name,'New_York'); % retrieve TZ of specific interest
Z2=A(contains(A.Name,'Khartoum');
u=Z2.UTCOffset+Z2.DSTOffset-(Z1.UTCOffset+Z1.DSTOffset) % offset including DTS
u =
7
The problem with this is that I don't believe the table will update the DTS offset with time of year; it's just the value used in the location. So, this is probably not viable actual solution lacking a test for whether DST is in effect in both locations at the time of interest.