Search code examples
angulartypescriptdurationluxon

How do I format a Luxon duration of seconds toHuman() showing both minutes and seconds?


I have a time expressed as seconds (ex. 25, 30, 60 or 94, 315, etc. Using Luxon I want to show it like this

25 sec
30 sec
1 min
1 min 34 sec
5 min 15 sec

How would I format Luxon to do this?

Here is what I currently have but it isn't correct as it only shows seconds.

{{duration.fromObject({ seconds: 315}).toHuman({ unitDisplay: "short" })}}

This only shows seconds 315. I want it to show:
5 min 15 sec

I'm using these links link1 link2


Solution

  • Combine DateTime and Interval:

    1. Convert the value to an Interval: Interval.fromDateTimes(DateTime.fromSeconds(0), DateTime.fromSeconds(315)

    2. Transform the interval to a duration with units option: interval.toDuration(['minutes', 'seconds']) // .toObject() => {minutes: 5, seconds: 15}

    Then your code will look like this:

    import { DateTime, Interval } from "luxon";
    // ...
    {{Interval.fromDateTimes(DateTime.fromSeconds(0), DateTime.fromSeconds(315)).toDuration(['minutes', 'seconds']).toHuman({ unitDisplay: "short" })}}