Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Convert a datetime, knowing its time zone, to UTC

I must convert a date time, given its time zone, year, month, day, hours and minutes to an ISO string.

For example, given the following parameters:

{
 timeZone: 'Europe/Paris',
 year: 2020,
 month: 11,
 day: 18,
 hours: 14,
 minutes: 44,
}

I want to build the ISO string corresponding: 2020-11-18T13:44:00.000Z (notice the hour shift there)

You can do this the other way around pretty easily, either with the Intl.DateTimeFormat or the toLocaleDateString/toLocaleTimeString methods, but this way I can't find a proper solution... If I overlooked any source of information, please let me know.

EDIT (see comments):

The perk of using a time zone and not a GMT string, such a 'GMT +01:00', is that I won't have to handle time changes. As you may know, the time zone 'Europe/Paris' is 'GMT +01:00' in the winter but 'GMT +022:00' in the summer... And I can't find a proper way to map the timezone to any UTC offset

Thank you in advance for your help

SOLUTION:

As suggested below, using Luxon we can do

const timeObject = { day, month, year, hours, minutes, zone: timeZone };
const date = DateTime.fromObject(timeObject).toUTC().toString();

Matt also suggested the for now experimental Temporal feature.

like image 505
rguerin Avatar asked Oct 29 '25 05:10

rguerin


1 Answers

When Temporal is available in your browser engine (or if you use a polyfill) then just do this:

Temporal.ZonedDateTime.from({
  timeZone: 'Europe/Paris',
  year: 2020,
  month: 11,
  day: 18,
  hour: 14,
  minute: 44,
}).toInstant().toString();
// => '2020-11-18T13:44:00Z'
like image 79
Justin Grant Avatar answered Oct 31 '25 20:10

Justin Grant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!