Durations
overview
A duration is both a quantity of time and a distance between two instants.
To format durations, we use either:
- the Luxon library
- the built-in Intl.DurationFormat (more limited).
output durations (Luxon)
pick the duration units
We pick the duration units (if needed) so that the subsequent outputs make use of them.
rescale()automatically determines which units to use. It eagerly uses the higher magnitude units. Then it 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, human friendly duration
toHuman() outputs a human-readable description. It uses the units that were set as the current units (configuration).
dur.toHuman() // '1 day, 12 hours'
dur.toHuman({ listStyle: "long" }) // '1 day and 12 hours'
duration instantiation (Luxon)
The way we instantiate determines the defaults units being used.
milliseconds quantity
const dur = Duration.fromMillis(1_000_000) // 1000 seconds
// dur.toHuman() // '1000000 milliseconds'
Duration.fromMillis(d2.getTime() - d1.getTime())
calendar components as a quantity
const dur = Duration.fromObject({ hour: 36 })
// dur.toHuman() // '36 hours'
from difference between two DateTime instances
In this instantiation, we can set the units being used:
const dur = zdt2.diff(zdt1, ["years", "months", "days"])
// dur.toHuman() // "3 years, 2 months, 14 days"