I have a function and I want to convert date strings from the user’s timezone to UTC. For instance, I have this date Tue, Jun 18 2024, 12:00
, in GMT+3.
Here is my function:
const convertToUTC = (localDateStr) => {
const localTimezone = dayjs.tz.guess();
console.log(localDateStr);
const date1 = dayjs(localDateStr).format();
console.log(date1);
const date2 = dayjs(date1);
console.log(date2);
const utcDate = date2.utc();
console.log(utcDate.format());
const formattedDate = utcDate.format('ddd, MMM D YYYY, HH:mm UTC');
console.log(formattedDate);
return formattedDate;
}
It takes one argument, a local date string. My logic was this: Take the date string, parse it with dayjs library to make it an ISO 8601 format string, then parse that string, make it in UTC with .utc(), and finally format it again the way I like. And it works. My initial date string Tue, Jun 18 2024, 12:00
is converted to Tue, Jun 18 2024, 09:00 UTC
as it should be. The problem here is that when I test this with a google dev tool (which I found in dev tools, pressed the 3 dots, more tools -> Sensors) and changed the location with the override, it works on some dates. On dates with non-Latin characters, such as Tokyo, Shanghai, Mumbai, and Moscow timezones, which has dates like this Tue, 6月 18 2024, 18:00
, my function does not work. It pops invalid date in the console. On dates with Latin-based characters (such as in gb and us locale), it works fine.
Do I need to add the locale somehow, in order to parse the date string correctly? I cannot really make it work on such dates. Any help or guidance would be appreciated. Thank you.