moment / moment-timezone

Timezone support for moment.js
momentjs.com/timezone
MIT License
3.82k stars 837 forks source link

Resolve an offset to a timezone name #651

Closed tsheaff closed 2 years ago

tsheaff commented 6 years ago

Related to https://github.com/moment/moment-timezone/issues/371

I understand that, with Daylight Savings or other time-changing laws, a particular time zone does not have a stable offset over time. But if I just need to convert +09:00 to a timezone name for the next few milliseconds while I respond to a single request, and I don't want to update all of my moment().tz(timezone) parsers, I'd love to be able to convert +09:00 into a timezone name (e.g. America/New_York) that has that offset right now.

The naive approach of iterating through them all until I find one that matches would work, but wondering if there's a better way.

tsheaff commented 6 years ago

Or if there's an elegant way to extend moment-timezone's functionality to support parsing timezones with offset of style -07:30 or +09:00 (regex [+|-]\d\d:\d\d)

tsheaff commented 6 years ago

@ellenaua @timrwood any thoughts on this?

nVitius commented 6 years ago

@tsheaff What you're looking for can be accomplished using moment.utcOffset()

tsheaff commented 6 years ago

@nVitius can you clarify? I don't think that's sufficient. I need to go the other direction, from the offset (e.g. -7) to the name (e.g. America/Los_Angeles)

nVitius commented 6 years ago

Ah, okay. I didn't read your question right the first time. I thought you wanted to set a timezone on a date given just the offset.

I agree that this functionality would be useful though. Maybe something like moment.tz.guess(moment()) could be implemented.

tsheaff commented 6 years ago

Yeah something like that. But guess() on the browser is implemented by changing the clock several times quickly I believe. Almost all server systems I've used are just on UTC time and would not appreciate global clock changes.

prakis commented 6 years ago

Hello @tsheaff found any elegant solutions to get timezone name from offset (ex:- +09:00 ) ?

pedro-mass commented 6 years ago

Wondering the same...The docs say there is a zone object that we shouldn't need to use, but maybe we could use that?

Not much documentation though, and the type files aren't showing anything either

I did see .zoneName() | .zoneAbbr() but that always returns undefined (although I've set it when creating the object)

tsheaff commented 5 years ago

By the way this is working for me (timezoneOffset is like +05:00 or -10:30 and declared in the outer scope)

_.find(moment.tz.names(), (timezoneName) => {
    return timezoneOffset === moment.tz(timezoneName).format('Z');
});

Obviously not the most efficient thing but it works

prakis commented 5 years ago

@tsheaff That's a clean solution. Thanks for sharing.