TAGS :Viewed: 7 - Published at: a few seconds ago

[ javascript parse datetime string in NewYork Timezone ]

I have a datetime string which represents a local New York time.

12/30/2020 12:00 pm

I want to parse it in javascript to get EPOCH. The parsing has to work for users which may be in different timezones.

What I did now is

moment("07/13/2015 01:45 am -04:00", 'M/D/YYYY h:mm a Z').unix()

but this is not good because I had to hardcode

-04:00

and assume that the date I'm parsing is Eastern Daylight Saving Time.

Answer 1


Use the moment-timezone add-on.

moment.tz("12/30/2020 12:00 pm", "M/D/YYYY h:mm a", "America/New_York").unix()

Also, be aware that there's no guarantee that the rules for any particular time zone will persist into the future. Who knows if by 2020 if the US government won't change the DST rules again like they last did in 2007. Sure, it's not likely to affect a date in December, but in the general case you can't be certain. Especially when you consider that other time zones have changes often - about a dozen or more changes globally every year.

Oh, and one minor petpeeve... You said:

... to get EPOCH.

The word epoch means "the start of something". The Unix Epoch is 1970-01-01T00:00:00Z. It's never anything else. The value you get back from a unix timestamp is based on the epoch - but it is not itself an epoch. "Epoch Time" is a misnomer. (There are other epochs used in computing, but not with relation to Unix Time).