day.js is not converting UTC to local time

13,131

Solution 1

Both Moment and Day.js only support millisecond precision, however they differ in behavior when more than 3 decimals are passed in for parsing.

  • Moment will ignore the extra decimals, but will still use its own parsing logic
  • Day.js reverts to the Date.parse function

In the latter case, there is no UTC awareness, so you get local time, despite being passed through the dayjs.utc function.

This was brought up in Day.js issue #544, and closed by the owner of that library without any change.

You can work around this by trimming the string to truncate the extra decimals.

dayjs.utc('2020-04-22T14:56:09.388842'.substring(0, 23))

Then it will parse UTC correctly, and the rest of your logic will work accordingly.

(Alternatively, you could append a Z to the string)

Solution 2

I used:

dayjs(date).utc('z').local().tz(ianaCode).format('ddd, MMM D, H:mm z')

Example:

dayjs('2021-06-08T24:00:00').utc('z').local().tz('America/Detroit').format('ddd, MMM D, H:mm z')

Share:
13,131
rolu
Author by

rolu

Web Developer interested in Word Press.

Updated on June 15, 2022

Comments

  • rolu
    rolu almost 2 years

    I am running into an issue trying to convert momentjs over to day.js.

    In moment, I converted utc to local time via moment.utc('2020-04-22T14:56:09.388842').local().format('MM/DD/YY h:mm A') which returns 04/22/20 9:56 AM.

    When I convert with day.js via dayjs.utc('2020-04-22T14:56:09.388842').local().format('MM/DD/YY h:mm A'), I get 04/22/20 2:56 PM; I am importing the utc plugin.

    I put an example in jsfiddle here: https://jsfiddle.net/obdg74sp/2/

    Has anyone ran into this issue and if you did, how did you resolve it?

    Thank you.