WillD
WillD

Reputation: 6512

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?

Upvotes: 21

Views: 68851

Answers (2)

VincenzoC
VincenzoC

Reputation: 31482

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/[email protected]/build/global/luxon.js"></script>

Upvotes: 28

Rishab
Rishab

Reputation: 1522

You can refer the following luxon function:

  1. isInDST https://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html#instance-get-isInDST

To check whether current time is based on DST or not!

  1. toUTC : function to convert to UTC based time

https://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html#instance-method-toUTC

Upvotes: 1

Related Questions