Reputation: 16716
Timezones is constant pain in every datetime library I tried. So here's the question, suppose you have a UTC datetime provided as string: 2019-06-25T05:00:00Z
. How do you create a UTC DateTime object out of it (I use luxon, but answer can be in terms of any library)?
console.info(luxon.DateTime.fromISO('2019-06-25T05:00:00Z').toSQL());
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>
When I run the snippet above I get:
2019-06-25 09:00:00.000 +04:00 // local timezone
While I need:
2019-06-25 05:00:00.000 -00:00 // UTC
Upvotes: 6
Views: 7545
Reputation: 1073968
Three options for you:
1) Luxon's documentation says you could use fromISO
to get a DateTime
from it. That parses the string correctly. Looks like to get it formatted the way you want, you have to tell it to use the zone UTC, but that's because it's formatting on output:
const {DateTime} = luxon;
console.info(DateTime.fromISO('2019-06-25T05:00:00Z', { zone: "UTC"}).toSQL());
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>
You could also use setZone("UTC")
on the result of fromISO
.
2) JavaScript's built-in Date
object will parse that as UTC (new Date(yourString)
), since it's in the format defined in the spec. You can then use the UTC methods on it to get the UTC information (getUTCHours
, etc.), or you can use the local date/time methods on it to get the local information (getHours
, etc.). You can also use toISOString
to get a UTC string:
console.info(new Date('2019-06-25T05:00:00Z').toISOString());
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>
3) Moment would also happily do so.
console.info(moment.utc('2019-06-25T05:00:00Z').toISOString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
If you need +00:00
instead of Z
, you can throw a replace
at it, or with Luxon or Moment they offer full formatting options.
Upvotes: 6