For a while, I've been using dayjs in my angular project to convert timestamps from UTC to localtime. However, after my recent update, this functionality stopped working. This isn't the first issue I've encountered with dayjs, so I decided to create a utility class to handle timestamp conversion centrally. Unfortunately, this utility class fails in Angular 12, 14, and even in a typescript test project on stackblitz. Upon investigation, I found an issue with the tz function of dayjs as the isValid function returns false.
tl;dr Converting a dayjs date to another timezone in typescript results in an invalid date:
dayjs.utc(time).tz('America/New_York').isValid()
This returns false. To showcase this issue, I created a small test project on stackblitz. Here is the TimeUtil class:
import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
dayjs.extend(timezone);
dayjs.extend(utc);
export class TimeUtil {
public timeZoneLocal: string = dayjs.tz.guess();
public debug(time: dayjs.Dayjs): Date {
console.log('Debug Information:');
console.log('time:', time);
console.log('utc:', dayjs.utc(time));
console.log('tz:', dayjs.utc(time).tz('America/New_York'));
console.log('time valid? ', time.isValid() ? 'Yes' : 'No')
console.log('utc valid? ', dayjs.utc(time).isValid() ? 'Yes' : 'No')
console.log('tz valid? ', dayjs.utc(time).tz('America/New_York').isValid() ? 'Yes' : 'No')
return dayjs.utc(time).tz('America/New_York').toDate();
}
public toLocal(time: dayjs.Dayjs): Date {
return dayjs(time).tz(this.timeZoneLocal).toDate();
}
}
The toLocal Method always returns null. To find the error, I wrote a debug method. The output of the debug method is:
Debug Information:
time: 2023-01-10T05:34:00.000Z
utc: 2023-01-10T05:34:00.000Z
tz: null
time valid? Yes
utc valid? Yes
tz valid? No
I activated esModuleInterop
and allowSyntheticDefaultImports
.
How can I fix my toLocal method?
Is there a simpler way to parse an utc iso datestring and convert it to a local date?
This issue seems to be related to the operating system as Firefox, Chrome, and Intellij are affected. Interestingly, everything works fine on my work PC and Android Tablet.