6

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?

João Pedro
  • 794
  • 2
  • 12
  • 28
  • Please read the Day.js documentation about string parsing and "Parsing in Zone". – str Sep 22 '20 at 09:40

6 Answers6

12

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)
donquixote
  • 365
  • 3
  • 10
3

try this:

dayjs.extend(utc)
dayjs.extend(timezone)
dayjs("2020-09-21 20:30").tz("Asia/Taipei")
Nbody
  • 1,168
  • 7
  • 33
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.

Petter
  • 99
  • 4
  • 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. – Lynx Jul 05 '23 at 19:14
2

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

João Pedro
  • 794
  • 2
  • 12
  • 28
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?

olga_babic
  • 1,600
  • 3
  • 9
  • 18
1

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

Jumshud
  • 1,385
  • 1
  • 13
  • 19