How to use moment-tz.js to parse tz like “GMT-08:00”

后端 未结 2 1490
渐次进展
渐次进展 2021-01-28 12:02

I try to run this js

return function(milliSeconds, timeZoneId) {
    if (milliSeconds == 0) {
        return \"\";
    }
    var now = moment();

    return now.         


        
2条回答
  •  心在旅途
    2021-01-28 12:54

    As moment.tz(..., String) docs states:

    The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.

    A time zone identifier is something like 'America/New_York' or 'Europe/Rome', "GMT-08:00" is not a valid input.

    In your case you can use moment(Number) and then:

    • converting to given zone using tz() function
    • or set offset using utcOffset(String)

    var milliSeconds = "1524578400000";
    var timezoneId = "GMT-08:00";
    
    var timeInt = parseInt(milliSeconds, 10)
    var m1 = moment(timeInt).tz('America/Los_Angeles');
    console.log(m1.format('MMM D, YYYY H:mm:ss'));
    
    var offset = timezoneId.substring(3);
    var m2 = moment(timeInt).utcOffset(offset);
    console.log(m2.format('MMM D, YYYY H:mm:ss'));
    
    

    Please note that:

    • moment formatting tokens are case sensitive, so you have to use YYYY for years and D for day of the month (d is day of the week)
    • 1524578400000 is 2018-04-24 14:00:00 UTC, I'm missing why you are expecting 5am as output.

提交回复
热议问题