Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 301
Sgraffite Avatar asked Jan 28 '15 17:01

Sgraffite


People also ask

How do I remove moments from my timezone?

momentDate. format('YYYY-MM-DDTHH:mm:ss') + '00:00'; This would remove the timezone and then append the '00:00' part back in.

How do I display timezone in MomentJS?

var result = moment(someDate). format("MM/DD/YYYY HH:mm A Z");

How do I change timezone in MomentJS?

To change the default time zone, use moment. tz. setDefault with a valid time zone.

How do I get the current time in MomentJS?

To get the current date and time, just call javascript moment() with no parameters like so: var now = moment(); This is essentially the same as calling moment(new Date()) .


3 Answers

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.

like image 119
musicfuel Avatar answered Oct 20 '22 15:10

musicfuel


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

moment().utcOffset(0, true).format()
like image 34
merqlove Avatar answered Oct 20 '22 15:10

merqlove


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.

like image 2
Sgraffite Avatar answered Oct 20 '22 14:10

Sgraffite