Sub topic 13
Working with Temporal.Duration
A Temporal.Duration is a length of time, such as "1 hour 30 minutes" or "2 months 14 days", with no start or end point attached. You get durations from arithmetic and from differences, and you also create them yourself. This chapter covers how durations store their fields, why they do not balance on their own, and how to convert them into a single number.
This chapter assumes you know modern JavaScript, the arithmetic methods from the previous chapters, and how to make Temporal available, either natively or through @js-temporal/polyfill. Every example uses the global Temporal.
What a Duration Stores
A duration holds ten separate fields. Temporal does not convert them into one number of milliseconds:
| Group | Fields |
|---|---|
| Calendar units | `years`, `months`, `weeks`, `days` |
| Time units | `hours`, `minutes`, `seconds` |
| Subsecond units | `milliseconds`, `microseconds`, `nanoseconds` |
Each field is kept as you wrote it. That is the main thing to understand about durations. { minutes: 130 } stays 130 minutes and does not become 2 hours 10 minutes until you ask for that.
Creating Durations
You can create a duration from a property bag, from an ISO 8601 duration string, or with the constructor. The constructor takes the fields in order, from largest to smallest.
const a = Temporal.Duration.from({ hours: 1, minutes: 30 });
const b = Temporal.Duration.from('PT1H30M');
const c = new Temporal.Duration(0, 0, 0, 0, 1, 30); // years..minutes
console.log(a.toString()); // 'PT1H30M'
console.log(Temporal.Duration.compare(a, b)); // 0
console.log(c.hours, c.minutes); // 1 30
const unbalanced = Temporal.Duration.from({ minutes: 130 });
console.log(unbalanced.toString()); // 'PT130M'An ISO duration string starts with P (period). Date units come next, then T, then time units: P1Y2M3DT4H5M6S. Because the T separates the two halves, P1M means one month and PT1M means one minute.
Signs
A duration can be negative, but all its non-zero fields must share the same sign. Mixing signs throws an error:
const back = Temporal.Duration.from({ hours: -2, minutes: -15 });
console.log(back.toString()); // '-PT2H15M'
console.log(back.sign); // -1
console.log(back.negated().toString()); // 'PT2H15M'
console.log(back.abs().toString()); // 'PT2H15M'
console.log(Temporal.Duration.from({}).blank); // true
try {
Temporal.Duration.from({ hours: 1, minutes: -30 });
} catch (e) {
console.log(e instanceof RangeError); // true
}Use sign (-1, 0, or 1) and blank (true when every field is zero) to inspect a duration. You do not need to check each field yourself.
Balancing with round
Balancing means moving overflow from a smaller unit into a larger one, for example turning 130 minutes into 2 hours 10 minutes. Call round with a largestUnit to balance a duration:
const long = Temporal.Duration.from({ minutes: 130 });
console.log(long.round({ largestUnit: 'hour' }).toString()); // 'PT2H10M'
const big = Temporal.Duration.from({ seconds: 100000 });
console.log(big.round({ largestUnit: 'hour' }).toString()); // 'PT27H46M40S'
console.log(big.round({ largestUnit: 'day' }).toString()); // 'P1DT3H46M40S'If you leave out smallestUnit, nothing is rounded away, so the call only balances. The chapter on rounding covers smallestUnit, increments, and rounding modes.
Converting to One Number with total
Use total when you need one numeric value, such as a total in minutes for billing or charts. The result can be a fraction:
const meeting = Temporal.Duration.from({ hours: 1, minutes: 30 });
console.log(meeting.total({ unit: 'minute' })); // 90
console.log(meeting.total({ unit: 'hour' })); // 1.5
console.log(meeting.total('second')); // 5400You can pass a plain unit string as a shorthand when you need no other options.
Calendar Units Need relativeTo
Time units have fixed lengths. An hour is always 60 minutes. Calendar units do not: a month can be 28 to 31 days long, and a day in a time zone can be 23 or 25 hours long around a daylight saving change. To convert these units, Temporal needs a starting point, which you pass as relativeTo.
const oneMonth = Temporal.Duration.from({ months: 1 });
console.log(oneMonth.total({ unit: 'day', relativeTo: '2024-02-01' })); // 29
console.log(oneMonth.total({ unit: 'day', relativeTo: '2024-03-01' })); // 31
try {
oneMonth.total({ unit: 'day' });
} catch (e) {
console.log(e instanceof RangeError); // true
}
const oneDay = Temporal.Duration.from({ days: 1 });
console.log(oneDay.total({ unit: 'hour' })); // 24 (no relativeTo: days are 24 h)
const springForward = Temporal.ZonedDateTime.from(
'2024-03-10T00:00[America/New_York]'
);
console.log(oneDay.total({ unit: 'hour', relativeTo: springForward })); // 23relativeTo accepts a PlainDate, a ZonedDateTime, or a string or property bag that parses to one of them. A PlainDate resolves month lengths. A ZonedDateTime also resolves day lengths in that time zone.
Combining and Comparing Durations
add and subtract combine two durations, and the result is balanced up to the largest unit present in either input. These methods only work with days and smaller units. When either duration contains years, months, or weeks, they throw a RangeError, because the result would depend on a start date. In that case, apply both durations to a date one after the other.
const t1 = Temporal.Duration.from({ hours: 1, minutes: 45 });
const t2 = Temporal.Duration.from({ minutes: 30 });
console.log(t1.add(t2).toString()); // 'PT2H15M'
console.log(t1.subtract(t2).toString()); // 'PT1H15M'
// Calendar units: apply to a date instead
const start = Temporal.PlainDate.from('2024-01-31');
const end = start.add({ months: 1 }).add({ weeks: 2 });
console.log(end.toString()); // '2024-03-14'
// Replace individual fields
console.log(t1.with({ minutes: 0 }).toString()); // 'PT1H'Temporal.Duration.compare(a, b, { relativeTo }) returns -1, 0, or 1. Like total, it needs relativeTo whenever calendar units are involved. Comparing { months: 1 } with { days: 30 } has no single answer: the month is longer starting in January and shorter starting in February.
Common Mistakes
- Expecting automatic balancing.
Duration.from({ seconds: 3600 }).hoursis0, not1. Callround({ largestUnit: 'hour' })first. - Reading one field as the total.
duration.minutesis only the minutes field. To get the whole length in minutes, usetotal('minute'). - Forgetting relativeTo. Any
total,round, orcomparecall that involves months or years throws without it. - Mixed signs. Building a duration from user input such as
{ hours: 2, minutes: -10 }throws. Normalize the input before you create the duration.
Exercise
Given const d = Temporal.Duration.from({ hours: 2, minutes: 75 });, what do d.toString(), d.round({ largestUnit: 'hour' }).toString(), and d.total('minute') return?
Show answer
'PT2H75M' (fields are stored as written), 'PT3H15M' (balanced), and 195.
Exercise
Why does Temporal.Duration.from({ months: 2 }).total({ unit: 'day' }) throw, and how would you get the number of days in two months starting on 2024-01-01?
Show answer
Months have no fixed length, so a RangeError is thrown without a reference point. Pass one: total({ unit: 'day', relativeTo: '2024-01-01' }) returns 60, which is 31 days for January plus 29 for February in the 2024 leap year.
Exercise
Write code that returns the larger of two durations a and b, which may contain months, measured from the date 2024-06-01.
Show answer
const larger = Temporal.Duration.compare(a, b, { relativeTo: '2024-06-01' }) >= 0 ? a : b;