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

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

Asked on December 27, 2018 in Javascript.
Add Comment


  • 3 Answer(s)

    Instead of using moment-timezone one can use the UTC and local timezone. Because moment.js library has full function for UTC and the local time zone.

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

    Or one can use this code,

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

    By send the testDateUtc, back into the moment() constructor, it creates a clone. The testDateUtc is the object.Otherwise,If we called .local(), Instead of Local Date value it will change the testDateUTC value, and the Moments are silent here.

    In case our actual input consist of a time zone offset such as +00:00 or Z and so on, we have to parse it with moment. We do not need to use another functions like .utc and .Local. Look at the example code,

    var localDate = moment("2015-01-30T10:00:00Z");
    
    Answered on December 27, 2018.
    Add Comment

    Initially, we have to define the date format. Then create moment to set the UTC flag to true on the moment object. After that make localized moment which is conversion from the actual one. Finally from the localized moment object get the formatted string.

    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
    

    For more references:  http://momentjs.com/docs/#/manipulating/local/

    Answered on December 27, 2018.
    Add Comment

    Try to use this code,

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

    Where utc timestamp is the {{ time }} function.

    Answered on December 27, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.