简体   繁体   中英

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?

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM