How to convert Moment.js date to users local timezone?

后端 未结 4 1276
故里飘歌
故里飘歌 2020-12-01 02:17

I use the Moment.js and Moment-Timezone frameworks, and have a Moment.js date object which is explicitly in UTC timezone. How can I convert that to the current timezone of t

相关标签:
4条回答
  • 2020-12-01 03:00
    var dateFormat = 'YYYY-DD-MM HH:mm:ss';
    var testDateUtc = moment.utc('2015-01-30 10:00:00');
    var localDate = testDateUtc.local();
    console.log(localDate.format(dateFormat)); // 2015-30-01 02:00:00
    
    1. Define your date format.
    2. Create a moment object and set the UTC flag to true on the object.
    3. Create a localized moment object converted from the original moment object.
    4. Return a formatted string from the localized moment object.

    See: http://momentjs.com/docs/#/manipulating/local/

    0 讨论(0)
  • 2020-12-01 03:01

    Use utcOffset function.

    var testDateUtc = moment.utc("2015-01-30 10:00:00");
    var localDate = moment(testDateUtc).utcOffset(10 * 60); //set timezone offset in minutes
    console.log(localDate.format()); //2015-01-30T20:00:00+10:00
    
    0 讨论(0)
  • 2020-12-01 03:09

    Here's what I did:

    var timestamp = moment.unix({{ time }});
    var utcOffset = moment().utcOffset();
    var local_time = timestamp.add(utcOffset, "minutes");
    var dateString = local_time.fromNow();
    

    Where {{ time }} is the utc timestamp.

    0 讨论(0)
  • 2020-12-01 03:15

    You do not need to use moment-timezone for this. The main moment.js library has full functionality for working with UTC and the local time zone.

    var testDateUtc = moment.utc("2015-01-30 10:00:00");
    var localDate = moment(testDateUtc).local();
    

    From there you can use any of the functions you might expect:

    var s = localDate.format("YYYY-MM-DD HH:mm:ss");
    var d = localDate.toDate();
    // etc...
    

    Note that by passing testDateUtc, which is a moment object, back into the moment() constructor, it creates a clone. Otherwise, when you called .local(), it would also change the testDateUtc value, instead of just the localDate value. Moments are mutable.

    Also note that if your original input contains a time zone offset such as +00:00 or Z, then you can just parse it directly with moment. You don't need to use .utc or .local. For example:

    var localDate = moment("2015-01-30T10:00:00Z");
    
    0 讨论(0)
提交回复
热议问题