javascriptdatetimetimezonedatetime-conversionecmascript-temporal

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.


Solution

  • Using Luxon (the successor to Moment).

    // your input object
    const o = {
      timeZone: 'Europe/Paris',
      year: 2020,
      month: 11,
      day: 18,
      hours: 14,
      minutes: 44,
    };
    
    // create a Luxon DateTime
    const dt = luxon.DateTime.fromObject({
      year: o.year,
      month: o.month,
      day: o.day,
      hour: o.hours,
      minute: o.minutes,
      zone: o.timeZone
    });
    
    // convert to UTC and format as ISO
    const s = dt.toUTC().toString();
    
    console.log(s);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.25.0/luxon.min.js"></script>

    Of course, you could simplify if your input object used the same field names as Luxon needs.