Home  >  Q&A  >  body text

Display datetime without changing time zone using MomentJs

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粉952365143P粉952365143387 days ago613

reply all(2)I'll reply

  • P粉520545753

    P粉5205457532023-10-18 17:34:27

    You can set the offset manually using the utcOffset method. < /p>

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

    reply
    0
  • P粉066725148

    P粉0667251482023-10-18 11:31:31

    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.

    reply
    0
  • Cancelreply