Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

day.js is not converting UTC to local time

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.

like image 473
rolu Avatar asked Dec 23 '22 18:12

rolu


2 Answers

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)

like image 98
Matt Johnson-Pint Avatar answered Jan 04 '23 09:01

Matt Johnson-Pint


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')

like image 36
Camilo Patiño Avatar answered Jan 04 '23 09:01

Camilo Patiño