Search code examples
javascriptdatedatetimeluxon

How to get luxon to output ISO date format without a colon in the timezone


How to generate dates using luxon in the following format

2020-12-03T16:35:40.426+0100

I've tried to use

let format = "yyyy-MM-dd\'T\'HH:mm:ss.SSSZ"
let str = date.toFormat(format)

but I get

2020-12-03T15:32:00.000+1

Solution

  • From Luxon's table of tokens

    Z       narrow offset   +5
    ZZ      short offset    +05:00
    ZZZ     techie offset   +0500
    

    Thus, you can use ZZZ to emit the offset in the format you requested.

    However, be aware that combining this in the way that you asked would produce a string that is not compliant with ISO 8601.

    ISO 8601 (in section 4.3.2) provides two valid formats, "Basic" and "Extended":

    Basic format                Example
    YYYYMMDDThhmmss             19850412T101530
    YYYYMMDDThhmmssZ            19850412T101530Z
    YYYYMMDDThhmmss±hhmm        19850412T101530+0400
    YYYYMMDDThhmmss±hh          19850412T101530+04
    
    Extended format             Example
    YYYY-MM-DDThh:mm:ss         1985-04-12T10:15:30
    YYYY-MM-DDThh:mm:ssZ        1985-04-12T10:15:30Z
    YYYY-MM-DDThh:mm:ss±hh:mm   1985-04-12T10:15:30+04:00
    YYYY-MM-DDThh:mm:ss±hh      1985-04-12T10:15:30+04
    

    Most people use the extended format, and sometimes you will find the basic format (especially in URLs). But you have combined the date and time from the extended format with the offset from the basic format, which is not a supported combination.

    Unless you are locked into this for some reason, I suggest moving to either the basic or extended format.