MATLAB Answers


How can I set the time zone of a datetime object using a numerical offset?

Asked by Bruce Elliott on 29 Oct 2015
Latest activity Commented on by Peter Perkins
on 6 Nov 2015
I have an application where the user will identify a time zone by the offset from UTC in hours. He'll be defining a range of times in UTC as well, and I'd like to be able to create the corresponding datetime array for his designated time zone, so I'd like to be able to do this using the numerical value he input for the offset.
I can convert the number of hours to a properly formatted string and set that as the value of the TimeZone property, but it seems like there could be a simpler way to do it using the numerical value directly (as a duration, most likely) - sort of the opposite of the tzoffset function.
Can this be done?


Show 1 older comment
Bruce, that would be the way to do it. You could also have used '%+d', I think. Is that not working?
Just to make sure: the time zones you're referring to are not the usual "civil" time zones that we use in our everyday lives. For example, -05:00 is not the same thing as America/New_York. The former is a constant offset from UTC. The latter defines DST rules, including historic changes in those rules.
Peter - Yes that works. I was just wondering if there was a way to do it without have to use a formatted string. This will get particularly complicated if I do indeed want to use the civil time zones as you suggested. I might have to use some kind of look-up table with the IANA identifiers.
In fact .... that sounds like a worthwhile function to create, since I don't think Matlab has a built-in translator to go from UTC offset to IANA label.
If all they specify is an offset from UTC, you have no hope to turn that into a civil time zone without making strong assumptions. If you're willing to do that, the timezones function might be helpful.

Sign in to comment.

0 Answers