Set global time zone

前端 未结 5 552
北荒
北荒 2020-12-24 00:23

I am using Moment.js to handle dates in my web application. The server returns all the dates in milliseconds UTC. Now, I have to display the dates applying a specific timezo

相关标签:
5条回答
  • 2020-12-24 00:55
    1. npm install moment-timezone
    2. var moment = require('moment-timezone'); and use this object instead of usual moment.
    3. moment.tz.setDefault(String); where String is a time zone identifier.

    For example:

    var moment = require('moment-timezone');
    moment.tz.setDefault("America/New_York");
    

    Docs: https://momentjs.com/timezone/docs/

    0 讨论(0)
  • 2020-12-24 00:58

    You can set the default timezone in Moment by using:

    moment.tz.setDefault(String);
    

    For example

    moment.tz.setDefault("America/New_York");
    
    0 讨论(0)
  • 2020-12-24 01:00

    Use the moment-timezone library found on the same website: http://momentjs.com/timezone/ It let's you do things like:

    moment(utcDateTime).tz(settings.timezone).format(settings.dateFormat);
    

    I recommend implementing a user class/object that has a service function for translating UTC to the user's timezone. Have a look at this fiddle:

    http://jsfiddle.net/guidosch/ofd4unhu/4/

    The dates are served as UTC, but the view uses the date formatting method of the user class to adjust and format the UTC date according to the user's preferences.

    0 讨论(0)
  • 2020-12-24 01:14

    Having run into this problem in the past, my solution was to create a moment factory that provisioned moment objects rom a base configuration. You can make it as transparent as requiring moment - referencing your package and using the class just like moment - but in reality you are calling a moment wrapper object that provisions the moment implementations with the selected timeZone.

    0 讨论(0)
  • 2020-12-24 01:18

    I've not done extensive testing, but it looks right on cursory tests. I was able to do this with Moment Timezone 0.0.1:

    var serverTimezoneOffset = <?php echo timezone_offset_get(new DateTimeZone(date_default_timezone_get()), new DateTime('now')) / -60; ?>;
    moment.updateOffset(new Date().getTimezoneOffset()-serverTimezoneOffset);
    
    0 讨论(0)
提交回复
热议问题