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?
momentDate. format('YYYY-MM-DDTHH:mm:ss') + '00:00'; This would remove the timezone and then append the '00:00' part back in.
var result = moment(someDate). format("MM/DD/YYYY HH:mm A Z");
To change the default time zone, use moment. tz. setDefault with a valid time zone.
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()) .
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.
You can use the utcOffset method to set the offset manually.
moment().utcOffset(0, true).format()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With