Search code examples
javascripttypescriptdurationluxon

Parsing ISO 8601 like duration in Luxon


I have duration string that looks like:

1:16.352

where 1 is minutes part, 16 is seconds part and 352 is millisecond part.

I wanted to use Duration.fromISOTime but I get:

{
  "reason": "unparsable",
  "explanation": "the input \"1:16.352\" can't be parsed as ISO 8601"
}

Is there a clean way of parsing such duration in Luxon?


Solution

  • Duration.fromISOTime does not work since 1:16.352 is not an ISO 8601 time string, the hour part is missing (see ISO 8601 Times).

    A workaround to build a Luxon Duration object could be the following:

    const DateTime = luxon.DateTime;
    const Duration = luxon.Duration;
    
    const startOfHour = DateTime.local().startOf('hour').toMillis();
    const dt = DateTime.fromFormat("1:16.352", "m:ss.SSS"). toMillis();
    const dur = Duration.fromMillis(dt - startOfHour);
    console.log(dur.toFormat("m 'minute' s 'second' S 'millis'"));
    <script src="https://cdn.jsdelivr.net/npm/luxon@1.26.0/build/global/luxon.js"></script>