JavaScript, time zones, and daylight savings time

后端 未结 2 621
一个人的身影
一个人的身影 2020-12-19 09:10

Welcome to this week\'s episode of Yet Another Time Zone Question:

I\'ve done a fair bit of reading on SO, tried to manipulate moment.js and date.js

相关标签:
2条回答
  • 2020-12-19 09:48

    Ah, I think I finally see what you're saying. You want to say something like, "The current time in NYC is _" based on the time that's on the user's computer, and while there's support (at least in the docs) for setTimezone("EDT") there doesn't appear to be support for setTimezone("America/New York"). You'll either have to hard code the dates for when to switch between EDT and EST (based on current time GMT, which you can get from the user's computer), or use a 3rd party API (or do this on the server side).

    0 讨论(0)
  • 2020-12-19 09:57

    All comparisons with time should be done with getTime() of your instance. This returns the number of milliseconds since the UTC epoch. DST won't matter. You send the getTime() value to your server. Your clientside scripts will then convert this value back into a JavaScript Date object like so:

    mydate = new Date(longmillisFromAnotherTZ);
    

    Then use any method on mydate to display the date how you'd like. Does this make sense? I'm failing to see how there's an issue. I'd be happy to clear anything up though.

    Edit:

    Just to be 100% clear...

    If two different clients need to display their actions to each other in different time zones, I'm suggesting that you use only the value from (new Date()).getTime() and then save that to the server. The server then sends this value to each respective client. The client is then responsible for displaying it in its own appropriate locale.

    Also, if you want a library that is good for getting timezones and offsets, getTimezoneOffset() is known to be flakey, you should check out this library: http://www.pageloom.com/automatic-timezone-detection-with-javascript

    0 讨论(0)
提交回复
热议问题