Display datetime without changing time zone using MomentJs
P粉952365143
P粉952365143 2023-10-17 22:58:38
0
2
545

Sometimes I end up seeing a datetime on the website frontend that has been adjusted to a specific time zone, and I want it to display as-is regardless of the user's time zone.

For example, let's say I have this date:

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

-07:00 means it's Mountain Time, MomentJs knows this and will automatically adjust for users in other time zones. For example, let's say I display the date time with the following code:

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

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

P粉952365143
P粉952365143

reply all(2)
P粉520545753

You can set the offset manually using the utcOffset method.

moment().utcOffset(0, true).format()
P粉066725148

Use moment's utc() method to remove the time zone and display everything in universal time.

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

This will display UTC time without any time zone offset. If you want to display the time as recorded in the user/server time zone, you can parse the zone information when constructing the moment instance and have it use the time zone recorded in the parsed string.

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

Using either of these two methods, you should consider marking the time in some way to reflect the time zone it corresponds to. Failure to do so can cause a lot of confusion for the end user.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!