Stop javascript Date function from changing timezone offset

前端 未结 5 2131
长发绾君心
长发绾君心 2020-12-01 16:22

So I have iso date time that need to be converted from a string to date object. How do I keep date from converting it to local browser timezone.

new Date(\'         


        
5条回答
  •  醉酒成梦
    2020-12-01 16:35

    You cannot change this behavior of Javascript because it is the only simple way for Javascript to work. What happens is simply that Javascript looks at the time shift, computes the matching timestamp, and then asks the OS for the representation of this timestamp in the local time zone. What is key to understand here is that -05:00 is not an indication of time zone but simply a shift from UTC.

    Time zones are complex beasts that are just arbitrary political decisions. The OS provides a service to display time in the local time zone, but not in other time zones. To do that you have to take in account things like DST that are pretty much a hell.

    As always with time management, the only decent way to tackle this problem is to use a dedicated library. In Javascript, you'll find Moment.js and Moment.Timezone.js very helpful.

    Example http://codepen.io/Xowap/pen/XKpKZb?editors=0010

    document.write(moment('2013-07-18T17:00:00-05:00').tz('America/New_York').format('LLL'));
    

    As a bonus, you get a ton of formatting/parsing features from Moment.js.

    Please also note that as long as you use the ISO 8601, your date can be pinpointed to a precise moment, and thus be displayed in any timezone of your liking. In other words, JS "converting" your date doesn't matter.

提交回复
热议问题