Before this lesson

Understand JavaScript numbers, strings and objects, and the basic distinction between local time and UTC.

What you will be able to do

Distinguish instants from calendar dates and avoid treating display strings as calculation data.

Understand the mechanism

Date represents an instant through an epoch-based millisecond value, while displayed calendar fields depend on time zone. An appointment instant, a birthday and a recurring local-time rule are different models and should not be collapsed into ambiguous strings.

Exchange instants with explicit offsets or Z. Avoid relying on arbitrary regional date parsing. Date-only strings and local component construction have distinct semantics; define the intended business meaning first.

Intl.DateTimeFormat formats for users with an explicit locale and time zone. toISOString normalizes an instant rather than presenting local time. Keep the underlying value stable instead of formatting then reparsing for comparisons.

Subtracting timestamps gives elapsed milliseconds, but the same local time tomorrow is not universally 24 hours later because of time-zone transitions. Validate invalid dates before calculation. This example formats a fixed instant rather than implementing scheduling rules.

Runnable example

Run the JavaScript in the Console of a separate practice page. Re-run the complete example after changing its input.

const instant = new Date('2026-01-01T00:30:00Z');
if (!Number.isFinite(instant.getTime())) throw new Error('Invalid date');
for (const zone of ['Asia/Shanghai', 'America/New_York']) {
  const format = new Intl.DateTimeFormat('en-GB', {
    timeZone: zone, dateStyle: 'medium', timeStyle: 'short'
  });
  console.log(zone, format.format(instant));
}
console.log('Stored instant:', instant.toISOString());
console.log('Elapsed hours:', (new Date('2026-01-01T02:30:00Z') - instant) / 3600000);

Trace and verify

Expect 08:30 on January 1 in Shanghai and 19:30 on December 31 in New York, with formatter-dependent punctuation. Elapsed time is two hours. Switch locale and confirm ISO output is unchanged, then test an invalid input.

Common mistakes and boundaries

Some Date constructors use zero-based months while user-facing months are one-based. Device clocks are user-controlled and cannot solely enforce server-side expiry rules.

Practice challenge

Display a publication instant in Chinese and English while storing UTC. Show a friendly unknown-date message for invalid data.

Reference solution and reasoning

Validate first, then format with an explicit zone. Reuse a formatter across many records. A display fallback must not silently replace invalid data with today.

Further reading