rguerin
rguerin

Reputation: 2128

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.

Upvotes: 4

Views: 1884

Answers (3)

Justin Grant
Justin Grant

Reputation: 46763

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'

Upvotes: 3

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241868

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.

Upvotes: 1

Advaith Muralimohan
Advaith Muralimohan

Reputation: 1

here is my answer:

    var year = 2020;
    var month = 11;
    var day = 18;
    var hours = 14;
    var minutes = 44;
    var string = years + month + day + hours + minutes;

if you want to display the string on output:

    var year = 2020;
    var month = 11;
    var day = 18;
    var hours = 14;
    var minutes = 44;
    var string = years + month + day + hours + minutes;
    document.getElementById("demo").innerHTML = "time in string" + 
    string

Upvotes: -1

Related Questions