Display datetime with MomentJs without timezone conversion

JavascriptMomentjs

Javascript Problem Overview


Sometimes I end up with a datetime on the front end of a web site that has already been adjusted to a specific time zone, and I wish to display it exactly as is regardless of the user's timezone.

For example let's say I have this date:

> 2015-01-22T16:11:36.36-07:00

The -07:00 means it is in Mountain Time, and MomentJs knows this and will automatically adjust for users in other timezones. For example say I display the datetime with this code:

moment('2015-01-22T16:11:36.36-07:00').format('l LT')

A user in Central time (-06:00) will see the time as 5:11PM instead of 4:11PM. How can I tell MomentJs to not adjust for the user's timezone and display the datetime as is?

Javascript Solutions


Solution 1 - Javascript

Use the utc() method of moment to remove the timezone and display everything in universal time.

moment.utc('2015-01-22T16:11:36.36-07:00').format('l LT')

That will display the time as it is in UTC without any timezone offset. If you want to display the time as it was recorded in the user/server timezone you can parse the zone information when you construct a moment instance and have it use the timezone recorded in the parsed string.

moment.parseZone('2015-01-22T16:11:36.36-07:00').format('l LT');

With either of these approaches you should consider labeling the time in some way to reflect the timezone the time corresponds to. Failing to do this could lead to a lot of confusion for the end users.

Solution 2 - Javascript

You can use the utcOffset method to set the offset manually.

moment().utcOffset(0, true).format()

Solution 3 - Javascript

I created an extension to display the datetime without trying to adjust to the user's timezone:

(function (moment) {
    moment.fn.nozone = function () {
        var m1 = moment(this);
        var offsetInMinutes = m1.utcOffset();
        return m1.utc().add(offsetInMinutes, 'm');
    };
}(moment));

This way it is easily reusable, even in javascript templates.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSgraffiteView Question on Stackoverflow
Solution 1 - JavascriptmusicfuelView Answer on Stackoverflow
Solution 2 - JavascriptmerqloveView Answer on Stackoverflow
Solution 3 - JavascriptSgraffiteView Answer on Stackoverflow