Format Durations with Luxon
Luxon uses Duration to manage durations.
instantiation
The unit(s) we pick for instantiation determines the default unit(s) being used:
Duration.fromMillis(1_000_000)
// dur.toHuman() // '1000000 milliseconds'
Duration.fromObject({ hour: 36 })
// dur.toHuman() // '36 hours'
We can build a duration from two DateTime instances, and set the units being used:
const dur = dt2.diff(dt1, ["years", "months", "days"])
// dur.toHuman() // "3 years, 2 months, 14 days"
control the unit(s)
We configure the duration units directly on the duration object, controlling subsequent outputs:
rescale()automatically determines which units to use. It eagerly uses the higher magnitude units, then sets them as the current units:
// dur.toHuman() // '1000000 milliseconds'
dur.rescale().toHuman() // '16 minutes, 40 seconds'
shiftTo()aims to set the units imperatively, and set them as the current units:
// dur.toHuman() // '1 day, 12 hours'
dur.shiftTo("hours", "minutes").toHuman() // '36 hours, 0 minutes'
dur.shiftTo("minutes").toHuman() // '2160 minutes'
output the configured duration
toHuman() outputs a human-readable duration. It uses the units as configured:
// 1.0 configuration
// 2.0 output
dur.toHuman() // '1 day, 12 hours'
dur.toHuman({ listStyle: "long" }) // '1 day and 12 hours'