dayjs is not converting timezones properly
Asked Answered
W

6

9

I'm trying to convert a date from my local time (Taipei UTC+8) to Los Angeles ( UTC-7) however dayjs conversion seems to be completely off :

dayjs("2020-09-21 20:30").tz("Asia/Taipei")

this results in Tue Sep 22 2020 05:30:00 GMT-0400 (Eastern Daylight Time) but it should have been Mon Sep 21 2020 02:30:00 GMT-0400 (Eastern Daylight Time)

any idea what's going on?

Wehrle answered 22/9, 2020 at 9:35 Comment(1)
Please read the Day.js documentation about string parsing and "Parsing in Zone".Lanti
B
17

I fixed using utc first and then format on local timezone

import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import tz from 'dayjs/plugin/timezone'

dayjs.extend(utc)
dayjs.extend(tz)

const timeZone = dayjs.tz.guess()
dayjs.utc(dateToConvert).tz(timeZone)
Baccalaureate answered 23/7, 2021 at 15:56 Comment(3)
THIS is the fix.Skyscape
What is utcDate?Kerchief
@Kerchief date which should be converted to desired tzBaccalaureate
H
3

try this:

dayjs.extend(utc)
dayjs.extend(timezone)
dayjs("2020-09-21 20:30").tz("Asia/Taipei")
Herra answered 22/9, 2020 at 9:46 Comment(0)
C
3
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import tz from 'dayjs/plugin/timezone'

dayjs.extend(utc)
dayjs.extend(tz)    

dayjs("2020-09-21 20:30").tz("Asia/Taipei").local().toDate();

dayjs("2020-09-21 20:30").tz("Asia/Taipei").local().toDate().toLocaleString();

.toString() and .toISOString() seem to always print the original date, before the timezone conversion, which may cause some confusion. toDate().toLocaleString() works.

Calenture answered 4/5, 2022 at 18:56 Comment(1)
This is the real answer. By not setting .local().toDate() it does not convert the date to the selected timezone. Really strange approach they took with that.Flat
W
2

I've fixed it by adding .local() after dayjs("2020-09-21 20:30").tz("Asia/Taipei").local()

Wehrle answered 22/9, 2020 at 11:4 Comment(0)
I
2

I'm using latest version of dayjs - 1.11.1 and react native v0.66.4. When I write:

dayjs("2020-09-21 20:30").tz("Asia/Taipei")

I get null as result. Does anybody have that problem?

Immovable answered 21/4, 2022 at 9:6 Comment(2)
Did you solve this ?Ferdy
check this github.com/iamkun/dayjs/issues/1377#issuecomment-775941749Solicitor
C
2

Without including any plugin like utc, timezone you can easily format utc date and pass it into dayjs like below:

const utcTimestamp = 1668414677538;
const utcFormat = dayjs(utcTimestamp).format('YYYY-MM-DDTHH:mm:ss+00:00');
console.log(dayjs(utcFormat).format('DD MMM, hh:mm a'));

It will do the trick

Chancelor answered 2/11, 2022 at 10:36 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.