day.js is not converting UTC to local time

rolu picture rolu · Apr 22, 2020 · Viewed 13.7k times · Source

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.

Answer

Matt Johnson-Pint picture Matt Johnson-Pint · Apr 22, 2020

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)