DateTimeFormat.formatRange Collapses Dates
Format start-to-end date spans with Intl.DateTimeFormat.formatRange to collapse shared months or years, and inspect segment sources via formatRangeToParts.
Code
const fmt = new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
timeZone: 'UTC',
});
const d1 = Date.UTC(2026, 4, 10);
const d2 = Date.UTC(2026, 4, 14);
const d3 = Date.UTC(2026, 5, 2);
console.log('same month :', fmt.formatRange(d1, d2));
console.log('cross month:', fmt.formatRange(d1, d3));
// formatRangeToParts labels each token as 'shared', 'startRange', or 'endRange'
const summary = fmt
.formatRangeToParts(d1, d2)
.map((part) => `${part.source}:${part.type}=${JSON.stringify(part.value)}`);
console.log('parts count:', summary.length);
console.log('sample part:', summary[0], '|', summary[2], '|', summary[4]);Output
Captured from a sandboxed run of this snippet in the build pipeline.
same month : May 10 – 14, 2026
cross month: May 10 – Jun 2, 2026
parts count: 7
sample part: shared:month="May" | startRange:day="10" | endRange:day="14"Runtime walkthrough — DateTimeFormat.formatRange Collapses Dates
Top-level bindings fmt, d1, d2, d3 hold the demo state — nothing sits inside a function scope.
What to watch for
- Zero-fetch snippet: every identifier resolves inside the language distribution.
Using it
The demo output is labeled (same month :, cross month:, parts count:); each label names the call that printed it.
Key statements
.map((part) => `${part.source}:${part.type}=${JSON.stringify(part.value)}`);
const fmt = new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
timeZone: 'UTC',
});
Interactive Tools for This Topic
Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.Cron Next Runs CalculatorCompute the next scheduled run times for a standard five-field cron expression, supporting ranges, lists, steps, and day-of-week naming semantics.ISO Week CalculatorFind the ISO 8601 week number, ISO week-year, week start and end dates, and day of year for any calendar date, with strict date validation.
FAQ
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. Its state lives in module-level bindings: `fmt`, `d1`, `d2`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.