Search code examples
javascriptluxon

LuxonJs formating date


I am getting from the DB a date in UTC

example: 2021-06-14T16:00:30.000Z

The idea is to change this date to LOCAL date so the output needs to be

2021-06-14T12:00:30.000Z

The problem is that doesn't matter what methods of Luxon use, I don't get that specific format (YYYY-mm-ddTHH:mm:ssZ)

How can I do this?

this piece of code is where I will put the Date getting from the DB, just need that format

const d = DateTime.fromISO('2021-06-14T16:00:30.000Z', { zone: 'America/Santiago' });

Solution

  • The ISO format is basically [date]T[localtime][offset]. The offset tells you with what UTC offset the local time is expressed. It could be like -04:00 (four hours behind UTC) or it could be "Z", which means +00:00, and generally implies not just the offset, but that the zone is UTC.

    So the problem is that with a "Z" on it, your expected string specifically indicates that it's not a local time, even though you've explicitly converted your DB's UTC time to a Santiago local time. In other words, the string you want specifies a different time than the DateTime object represents. That's why Luxon doesn't have a convenient method to do what you want; it doesn't really make sense.

    So here are a few options:

    d.toISO() //=> "2021-06-14T12:00:30.000-04:00", probably what you want
    d.toISO({ includeOffset: false }) //=> "2021-06-14T12:00:30.000", if you don't want the offset
    d.toUTC().toISO() // "2021-06-14T16:00:30.000Z", back to UTC
    

    If you really want the local time but with a Z, you can accomplish this, but note that anything parsing it will interpret it as expressing a different time (not a different local time, but a different millisecond in the history of the world) than the time in your DB, off by four hours:

    d.toISO({ includeOffset: false }) + "Z"; // => "2021-06-14T12:00:30.000Z"
    
    // OR
    
    d.setZone("utc", { keepLocalTime: true }).toISO() // => "2021-06-14T12:00:30.000Z"