Modern JS Temporal API — Date, Time & Math
Master wall-clock calendar primitives (PlainDate, PlainTime,
PlainDateTime), handle ISO durations with Temporal.Duration, perform pure mathematical
arithmetic with .add() and .subtract(), measure exact intervals using
.since() and .until(), and leverage the complete legacy-to-Temporal migration guide.
Table of Contents
20.1 Wall-Clock Calendar Primitives
Real-world applications frequently handle dates and times that have no meaningful timezone or instantaneous UTC coordinate attached — like birth dates, store opening hours, wedding anniversaries, or invoice due dates. Temporal provides dedicated wall-clock primitive objects:
Temporal.PlainDate
Temporal.PlainTime
Temporal.PlainDateTime
Instantiating Plain Primitives
// 1. PlainDate creation (Sensible 1-indexed month!):
const birthday = Temporal.PlainDate.from('1998-04-12');
console.log(Born on day , month ());
// 2. PlainTime creation:
const storeOpens = Temporal.PlainTime.from({ hour: 8, minute: 30 });
console.log('Store opens at:', storeOpens.toString()); // "08:30:00"
// 3. Merging Date and Time into a PlainDateTime:
const examDateTime = birthday.toPlainDateTime(storeOpens);
console.log('Exam scheduled:', examDateTime.toString()); // "1998-04-12T08:30:00"
Try Wall-Clock Studio in Playground
20.2
Temporal.Duration & ISO-8601 Durations
A Duration represents a physical quantity or span of time (e.g. 3 weeks, 2 days, and 45 minutes). Unlike legacy JavaScript where developers were forced to convert everything into messy millisecond integers (1000 * 60 * 60 * 24), Temporal.Duration models calendar and clock units natively.
Durations are serialized as ISO-8601 strings starting with P (Period), followed by date units (Y, M, W, D), a T separator, and time units (H, M, S). For example: P1Y2M14DT3H30M represents 1 year, 2 months, 14 days, 3 hours, and 30 minutes.
Working with Durations
// 1. Create a duration from an object:
const sprint = Temporal.Duration.from({ weeks: 2, days: 3 });
console.log(sprint.toString()); // "P2W3D"
// 2. Parse from standard ISO-8601 string:
const flightDelay = Temporal.Duration.from('PT3H45M');
console.log(Hours: , Minutes: );
// 3. Compute total in a single unit:
const totalSeconds = sprint.total({ unit: 'second', relativeTo: '2026-05-15' });
console.log('Total seconds in sprint:', totalSeconds);
// 4. Rounding durations:
const rounded = flightDelay.round({ smallestUnit: 'hour', roundingMode: 'halfExpand' });
console.log('Rounded flight delay:', rounded.toString()); // "PT4H"
Try Duration Inspector in Playground
20.3 Pure Date Arithmetic & Month Clamping
Date arithmetic in legacy JavaScript notoriously broke whenever calendar boundaries were crossed. In legacy Date, adding 1 month to January 31 caused an unintended spillover into March 3rd! Temporal performs pure, calendar-aware arithmetic:
const d = new Date('2026-01-31');
d.setMonth(d.getMonth() + 1);
// Result: 2026-03-03 (Silent overflow bug!)
const d = Temporal.PlainDate.from('2026-01-31');
const next = d.add({ months: 1 });
// Result: 2026-02-28 (Clamped to month end!)
Adding & Subtracting with Overflow Control
const startDate = Temporal.PlainDate.from('2026-01-15');
// Adding 45 days and 2 months:
const futureDate = startDate.add({ months: 2, days: 45 });
console.log('Future Date:', futureDate.toString());
// Subtracting 1 week:
const oneWeekAgo = startDate.subtract({ weeks: 1 });
console.log('One week prior:', oneWeekAgo.toString());
// Explicit overflow mode (reject throws RangeError instead of clamping):
try {
const rejected = Temporal.PlainDate.from('2026-01-31').add(
{ months: 1 },
{ overflow: 'reject' }
);
} catch (err) {
console.log('Caught expected overflow error:', err.message);
}
Try Month Clamping Studio in Playground
20.4
Measuring Intervals: .since() & .until()
To compute the exact elapsed duration between two dates, use startDate.until(endDate) or endDate.since(startDate). Both methods return a Temporal.Duration object and accept a largestUnit parameter to determine the granularity of the result:
Interval Measurement & Sorting
const today = Temporal.PlainDate.from('2026-05-15');
const launch = Temporal.PlainDate.from('2026-12-25');
// 1. Measure duration until launch with months as largest unit:
const countdown = today.until(launch, { largestUnit: 'month' });
console.log(Months: , Days: ); // Months: 7, Days: 10
// 2. Measure duration in total calendar days:
const totalDays = today.until(launch, { largestUnit: 'day' }).days;
console.log(Total days remaining: ); // 224 days
// 3. Chronological sorting using Temporal.PlainDate.compare:
const deadlines = [
Temporal.PlainDate.from('2026-12-25'),
Temporal.PlainDate.from('2026-01-15'),
Temporal.PlainDate.from('2026-06-30')
];
// Clean sorting without subtraction bugs:
const sorted = deadlines.toSorted(Temporal.PlainDate.compare);
console.log('Chronological deadlines:', sorted.map(d => d.toString()));
Try Interval Matrix in Playground
20.5 Interactive Practice Lab: Visual Date Math & Duration Engine
Select a starting date, apply a duration shift, and watch the calendar engine calculate safe, non-overflowing results in real time:
Start Date & Operations
Calculation Output
startDate.add({ months: 1 })
20.6 Hands-on Challenge: SaaS Subscription Renewal & Grace Period Engine
Coding ChallengeYou are implementing the billing subscription lifecycle for an enterprise SaaS platform. Given an initial signup date, calculate annual renewal deadlines, leap-safe anniversary dates, and whether an account is currently in its 14-day grace period:
- Accept an initial signup date string (e.g.
"2024-02-29"leap day). - Calculate the Next Annual Renewal Date using
.add({ years: 1 }). - Calculate the Grace Period Expiration by adding 14 days to the renewal date.
- Calculate total remaining days until expiration from a given check date using
.until().
/**
* Calculates SaaS renewal and grace period deadlines with Temporal precision.
*/
function calculateSubscriptionStatus(signupDateStr, checkDateStr) {
const signupDate = Temporal.PlainDate.from(signupDateStr);
const checkDate = Temporal.PlainDate.from(checkDateStr);
// 1. Calculate next annual renewal (Handles leap year 2024-02-29 -> 2025-02-28 safely)
const renewalDate = signupDate.add({ years: 1 });
// 2. Grace period ends 14 days after renewal date
const gracePeriodEnd = renewalDate.add({ days: 14 });
// 3. Days until expiration from today
const daysUntilGraceEnd = checkDate.until(gracePeriodEnd, { largestUnit: 'day' }).days;
const isExpired = Temporal.PlainDate.compare(checkDate, gracePeriodEnd) > 0;
const inGracePeriod = Temporal.PlainDate.compare(checkDate, renewalDate) >= 0 && !isExpired;
return {
signupDate: signupDate.toString(),
renewalDate: renewalDate.toString(),
gracePeriodEnd: gracePeriodEnd.toString(),
daysRemaining: Math.max(0, daysUntilGraceEnd),
inGracePeriod,
isExpired
};
}
// Verification on Leap Day Signup:
const result = calculateSubscriptionStatus('2024-02-29', '2025-03-05');
console.log(result);
// Output shows safe renewal on 2025-02-28 and grace period expiring 2025-03-14!
Date, adding 1 year to February 29th notoriously
spilled into March 1st. Temporal handles leap day clamping cleanly and deterministically.
20.7 Chapter Summary & Complete Migration Guide
Here is the definitive reference for refactoring legacy Date patterns into modern
Temporal in existing production projects:
| Goal | Legacy Date (Deprecated / Bug-Prone) |
Modern Temporal (Recommended) |
|---|---|---|
| Current Moment | new Date() |
Temporal.Now.instant() |
| Current Date Only | new Date() (stripping hours manually) |
Temporal.Now.plainDateISO() |
| Add 7 Days | d.setDate(d.getDate() + 7) (Mutates in place!) |
date.add({ days: 7 }) (Pure immutable copy) |
| Time Difference | (d2.getTime() - d1.getTime()) / 86400000 |
d1.until(d2, { largestUnit: 'day' }).days |
| Month Property | d.getMonth() (0 = January! 11 = December!) |
d.month (1 = January, 12 = December) |
| Format in Timezone | d.toLocaleString(..., { timeZone: 'Asia/Tokyo' }) |
instant.toZonedDateTimeISO('Asia/Tokyo').toLocaleString() |
Primitives & Durations
- Wall-Clock Isolation: Use
PlainDate,PlainTime, andPlainDateTimewhen dates have no timezone dependency. - First-Class Durations:
Temporal.Durationserializes cleanly to ISO-8601 strings (P1Y2M,PT30M) without millisecond math. - Immutable Guarantee: All arithmetic returns brand-new instances, ensuring 100% bug-free reactivity in React, Vue, and Angular.
Arithmetic & Clamping
- Deterministic Clamping: Adding a month to January 31 safely clamps to February 28/29 without unexpected March spillovers.
- Dual Interval Methods: Measure elapsed time from
d1tod2viad1.until(d2)ord2.since(d1). - Native Sorting: Use
Temporal.PlainDate.comparewithtoSorted()for clean chronological order.