Sub topic 20
Working Alongside Legacy Date Code
Most codebases that adopt Temporal still contain Date. Older libraries return Date objects, database drivers hand you Date values, and some APIs still expect a Date as input. This chapter shows how to move values across that boundary without silently changing them.
This chapter assumes you have read the earlier chapters on Temporal.Instant, ZonedDateTime, and converting between Temporal types. It also assumes Temporal is available, either natively or through the polyfill set up in the runtime support chapter.
The Shared Ground: Epoch Milliseconds
A Date object holds exactly one number: milliseconds since the Unix epoch (1970-01-01T00:00:00Z). It has no time zone of its own. Its "local" getters, such as getHours(), read that number through the host system's time zone.
That makes Date an exact-time type. Its closest Temporal match is Temporal.Instant, not PlainDateTime or ZonedDateTime. Every safe conversion goes through Instant and uses epoch milliseconds as the bridge.
Date to Temporal
import { Temporal } from '@js-temporal/polyfill';
const legacy = new Date('2024-03-15T12:00:00Z');
const instant = Temporal.Instant.fromEpochMilliseconds(legacy.getTime());
console.log(instant.toString()); // '2024-03-15T12:00:00Z'
// Add a time zone to get wall-clock fields
const ny = instant.toZonedDateTimeISO('America/New_York');
console.log(ny.toString()); // '2024-03-15T08:00:00-04:00[America/New_York]'If you want the same wall-clock reading that legacy.getHours() would give, use the system time zone explicitly:
const local = instant.toZonedDateTimeISO(Temporal.Now.timeZoneId());Writing Temporal.Now.timeZoneId() in the code shows that the result depends on the machine. With Date, that dependency is hidden.
toTemporalInstant
The Temporal proposal also adds Date.prototype.toTemporalInstant(). Runtimes that ship Temporal natively include it. The polyfill does not patch Date.prototype for you. It exports the function separately, and you can call it without modifying any global:
import { Temporal, toTemporalInstant } from '@js-temporal/polyfill';
const legacy = new Date('2024-03-15T12:00:00Z');
const instant = toTemporalInstant.call(legacy);
console.log(instant.equals(Temporal.Instant.from('2024-03-15T12:00:00Z'))); // truefromEpochMilliseconds(date.getTime()) works the same way in every environment, so it is the more portable choice.
Temporal to Date
Any exact-time Temporal value can be turned back into a Date through its epochMilliseconds property:
const zdt = Temporal.ZonedDateTime.from('2024-03-15T08:00[America/New_York]');
const asDate = new Date(zdt.epochMilliseconds);
console.log(asDate.toISOString()); // '2024-03-15T12:00:00.000Z'Plain types have no epochMilliseconds because they do not identify a moment. First choose a time zone, and a time of day when the value has none:
const due = Temporal.PlainDate.from('2024-03-15');
// Start of day in Paris
const startOfDay = due.toZonedDateTime('Europe/Paris');
console.log(new Date(startOfDay.epochMilliseconds).toISOString());
// '2024-03-14T23:00:00.000Z'
// A specific time in Paris
const at9 = due.toZonedDateTime({
timeZone: 'Europe/Paris',
plainTime: Temporal.PlainTime.from('09:00'),
});
console.log(new Date(at9.epochMilliseconds).toISOString());
// '2024-03-15T08:00:00.000Z'The ISO string shows March 14 because midnight in Paris (UTC+1 in mid-March) is 23:00 UTC the previous day. The conversion is correct, and the time zone is part of its meaning.
Common Errors at the Boundary
Lost precision
Instant stores nanoseconds and Date stores milliseconds. epochMilliseconds rounds down toward negative infinity, so a round trip drops the extra digits:
const precise = Temporal.Instant.from('2024-03-15T12:00:00.123456789Z');
console.log(precise.epochMilliseconds); // 1710504000123
const back = Temporal.Instant.fromEpochMilliseconds(new Date(precise.epochMilliseconds).getTime());
console.log(back.equals(precise)); // falseIf sub-millisecond precision matters, never send the value through Date. Store precise.toString() or precise.epochNanoseconds, which is a BigInt, instead.
Invalid Date
new Date('nonsense') does not throw. It produces a Date whose getTime() is NaN. fromEpochMilliseconds(NaN) throws a RangeError, but the message says nothing about where the bad value came from. Check for it explicitly:
function dateToInstant(date) {
if (!(date instanceof Date)) {
throw new TypeError('Expected a Date');
}
const ms = date.getTime();
if (Number.isNaN(ms)) {
throw new RangeError('Cannot convert an Invalid Date to Temporal.Instant');
}
return Temporal.Instant.fromEpochMilliseconds(ms);
}Date-only strings parsed as UTC
new Date('2024-03-15') means midnight UTC. A date-time string with no offset, such as '2024-03-15T00:00', means local midnight. Code that held the date-only form in a Date and later reads it in a local time zone gets the wrong day:
const d = new Date('2024-03-15');
const wrong = dateToInstant(d).toZonedDateTimeISO('America/New_York').toPlainDate();
console.log(wrong.toString()); // '2024-03-14'
const right = dateToInstant(d).toZonedDateTimeISO('UTC').toPlainDate();
console.log(right.toString()); // '2024-03-15'Find out which time zone the original code used when it created the value, and convert using that zone. If you can, parse the source string directly with Temporal.PlainDate.from and skip Date entirely.
Copying fields by hand
Avoid building a Date field by field. Date months start at 0, and Date.UTC maps the years 0–99 to 1900–1999:
const pd = Temporal.PlainDate.from('0050-06-01');
console.log(new Date(Date.UTC(pd.year, pd.month - 1, pd.day)).toISOString());
// '1950-06-01T00:00:00.000Z' (wrong century)
console.log(new Date(pd.toZonedDateTime('UTC').epochMilliseconds).toISOString());
// '0050-06-01T00:00:00.000Z'Containing Date with an Adapter
Convert at the edges of your system and keep Temporal everywhere in between. A small adapter module makes this a rule you can see in the code:
// legacy-adapter.js
import { Temporal } from '@js-temporal/polyfill';
export function fromLegacy(date, timeZone) {
const ms = date.getTime();
if (Number.isNaN(ms)) throw new RangeError('Invalid Date');
return Temporal.Instant.fromEpochMilliseconds(ms).toZonedDateTimeISO(timeZone);
}
export function toLegacy(value) {
if (value instanceof Temporal.Instant || value instanceof Temporal.ZonedDateTime) {
return new Date(value.epochMilliseconds);
}
throw new TypeError('Only Instant or ZonedDateTime can become a Date; add a time zone first');
}| Source | Target | Conversion | Needs a time zone? |
|---|---|---|---|
| `Date` | `Instant` | `Instant.fromEpochMilliseconds(d.getTime())` | No |
| `Date` | `ZonedDateTime` | via `Instant`, then `toZonedDateTimeISO(tz)` | Yes |
| `Date` | `PlainDate` | via `ZonedDateTime`, then `toPlainDate()` | Yes |
| `Instant` / `ZonedDateTime` | `Date` | `new Date(x.epochMilliseconds)` | No |
| `PlainDate` / `PlainDateTime` | `Date` | `toZonedDateTime(...)`, then `epochMilliseconds` | Yes |
Exercise
A library returns new Date('2024-07-04'). Your app needs the calendar date as a Temporal.PlainDate, and the server runs in America/Los_Angeles. Why does converting through Temporal.Now.timeZoneId() give the wrong answer, and what should you do?
Show answer
A date-only string passed to Date is parsed as midnight UTC. In Los Angeles that moment is the evening of July 3, so toPlainDate() returns 2024-07-03. Convert through 'UTC' instead: Temporal.Instant.fromEpochMilliseconds(d.getTime()).toZonedDateTimeISO('UTC').toPlainDate() gives 2024-07-04. Even better, parse the original string with Temporal.PlainDate.from.
Exercise
You turn Temporal.Instant.from('2024-01-01T00:00:00.000999Z') into a Date and back again. Is the result equal to the original? Explain.
Show answer
No. epochMilliseconds rounds down to whole milliseconds, so the 999 microseconds are lost and the round trip returns 2024-01-01T00:00:00Z. To keep full precision, store the ISO string or epochNanoseconds instead.
Exercise
Write a function plainDateToLegacy(plainDate, timeZone) that returns a Date for noon on that date in the given time zone.
Show answer
function plainDateToLegacy(plainDate, timeZone) { const zdt = plainDate.toZonedDateTime({ timeZone, plainTime: Temporal.PlainTime.from('12:00') }); return new Date(zdt.epochMilliseconds); }