Sgraffite
Sgraffite

Reputation: 1928

Display datetime with MomentJs without timezone conversion

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?

Upvotes: 65

Views: 97818

Answers (3)

merqlove
merqlove

Reputation: 3784

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

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

Upvotes: 43

Sgraffite
Sgraffite

Reputation: 1928

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.

Upvotes: 2

musicfuel
musicfuel

Reputation: 1680

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.

Upvotes: 86

Related Questions