Formatting ISO time with Luxon
Asked Answered
C

2

14

Using Luxon JS, I've been trying to format datetime to output in a certain format, using the native toISO function:

This is what I get:

"2018-08-25T09:00:40.000-04:00"

And this is what I want:

"2018-08-25T13:00:40.000Z"

I know that they are both equivalent in terms of unix time and mean the same thing except in a different format, I just want to be able to out the second string rather than the first. I looked through the Luxon docs but was unable to find any arguments/options that would give me what I need.

Cancer answered 5/5, 2021 at 19:4 Comment(2)
You need to convert the time to utc first. Try using date.toUTC().toISO() instead of date.toISO() .... date being your date object.Abject
Why use Luxon for that at all? The built–in Date.prototype.toISOString method does what you want.Distrust
D
18

As other already stated in the comments, you can use 2 approaches:

  • Convert Luxon DateTime to UTC using toUTC:

    "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
    
  • Use toISOString() method of JS Date.

You can use toJSDate() to get the Date object from a luxon DateTime:

Returns a JavaScript Date equivalent to this DateTime.

Examples:

const DateTime = luxon.DateTime;
const dt = DateTime.now();
console.log(dt.toISO())
console.log(dt.toUTC().toISO())
console.log(dt.toJSDate().toISOString())
console.log(new Date().toISOString())
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.js"></script>
Dixie answered 6/5, 2021 at 7:44 Comment(0)
H
4

From documentation I saw that in the method .fromISO of DateTime you can add an option object after the string of ISO date ("2018-08-25T09:00:40.000-04:00" in your example). In this object specify zone: utc like that:

const DateTime = luxon.DateTime;

const stringDate = "2018-08-25T09:00:40.000-04:00";

const dt = DateTime.fromISO(stringDate, {zone: 'utc'});

console.log('This is your date format', dt.toISO())
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.26.0/luxon.min.js"></script>
Hit answered 6/5, 2021 at 15:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.