javascriptluxon

luxon convert local time to utc given a timezone


A data source has an ISO-8601 datetime field without an offset.

Example: 2019-07-09T18:45

However, I know that the time in question is understood to be in the America/Chicago timezone.

How can I get a Luxon DateTime object of this time's equivalent in UTC?

I can do DateTime.fromISO('2019-07-09T18:45').plus({hours: 5}) ... but this will only be valid during half of the year (like now) when it is daylight savings time. Otherwise the offset would be .plus({hours: 6})

Does Luxon have a date-aware (and therefore DST-aware) method for converting from a specific zoned local time to UTC?


Solution

  • Since you know the timezone of you input date, you can use the zone option when parsing it. As fromISO docs states:

    public static fromISO(text: string, opts: Object): DateTime
    

    opts.zone: use this zone if no offset is specified in the input string itself.

    Then you can use toUTC to convert your DateTime to UTC:

    "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.

    Equivalent to setZone('utc')

    Here a live sample:

    const DateTime = luxon.DateTime;
    const d = DateTime.fromISO('2019-07-09T18:45', {zone: 'America/Chicago'});
    console.log(d.toISO());
    console.log(d.toUTC().toISO());
    <script src="https://cdn.jsdelivr.net/npm/luxon@1.16.0/build/global/luxon.js"></script>