Issue with luxon date time parsing when zone is present in string

Viewed 251

I am seeing error the input "06/09/22 02:14 CDT" can't be parsed as format MM/dd/yy HH:mm ZZZZ` when trying to get luxon date time from string.

DateTime.fromFormat("06/09/22 02:14 CDT","MM/dd/yy HH:mm ZZZZ")

Not sure what is the valid format I need to use when there is time zone in date string.

Thanks.

1 Answers

Issue is that you input contains CDT that is not recognized by Luxon since ZZZZ is not a valid token as explained in the Parsing -> Limitations section of the docs:

Not every token supported by DateTime#toFormat is supported in the parser. For example, there's no ZZZZ or ZZZZZ tokens. This is for a few reasons:

  • Luxon relies on natively-available functionality that only provides the mapping in one direction. We can ask what the named offset is and get "Eastern Standard Time" but not ask what "Eastern Standard Time" is most likely to mean.
  • Some things are ambiguous. There are several Eastern Standard Times in different countries and Luxon has no way to know which one you mean without additional information (such as that the zone is America/New_York) that would make EST superfluous anyway. Similarly, the single-letter month and weekday formats (EEEEE) that are useful in displaying calendars graphically can't be parsed because of their ambiguity.

You can add fixed string 'CDT' in your format or remove it completely from your input. You can use zone option (America/New_York in the example above, or America/Chicago in your use case) of DateTime#toFormat to take into account timezone offset.

Example:

const DateTime = luxon.DateTime;

const dt1 = DateTime.fromFormat("06/09/22 02:14 CDT","MM/dd/yy HH:mm 'CDT'", {zone: 'America/Chicago'})
const dt2 = DateTime.fromFormat("06/09/22 02:14", "MM/dd/yy HH:mm", {zone: 'America/Chicago'})

console.log(dt1.toISO());
console.log(dt2.toISO());
<script src="https://cdn.jsdelivr.net/npm/luxon@2.4.0/build/global/luxon.min.js"></script>

Related