MATLAB: Will you show me examples of changing time zones with datetime

datetimegmttime zones

I am currently working with data that comes in GMT. I want to get averages of when an event began and ended in local time (which is pacific standard time, a difference of 7 or 8 hours depending on the time of year). I don't want to just subtract 7 or 8, because datetime keeps track of daylight savings time, which is super helpful.
I change my time with the following code:
dateHourlyTZ = datetime(dateHourlyLocal, 'TimeZone','America/Los_Angeles','Format','d-MMM-y HH:mm:ss Z');
And as a result, I get dates that look like the following:
'1-Dec-1994 15:00:00 -0800'
'1-Dec-1994 16:00:00 -0800'
'1-Dec-1994 17:00:00 -0800'
'1-Dec-1994 18:00:00 -0800'
'2-Dec-1994 11:00:00 -0800'
'2-Dec-1994 15:00:00 -0800'
'5-Dec-1994 15:00:00 -0800'
'5-Dec-1994 16:00:00 -0800'
'18-Dec-1994 16:00:00 -0800'
'18-Dec-1994 17:00:00 -0800'
'23-Dec-1994 15:00:00 -0800'
'23-Dec-1994 16:00:00 -0800'
'23-Dec-1994 17:00:00 -0800'
'27-Dec-1994 15:00:00 -0800'
This is great except for the fact that it doesn't actually subtract the 8 hour time difference from the time. I considered maybe converting it to datestring and then manually subtracting the difference (whether it's 7 or 8 hours for the time of year), but when I convert it to datestring, I lose the -0800 or -0700.
The truth is I think I just don't understand all of what I can do with datetime or how the timezone change is applied. I've read all the Mathworks's info on datetime, but if you have any examples of how to manipulate timezones better or have any additional insight, that would be great. I'm not finding useful examples right now online!
Thanks a lot! — Ellyn

Best Answer

If you have not set the TimeZone on a datetime before, then it does not assume UTC to be converted. Setting the TimeZone for such an object does not change the associated time: it leaves the time alone and fills in the TimeZone field.
For an object that has a TimeZone filled out, changing the TimeZone will changed the displayed time.