Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.6 — Dates and Times
JavaScript · Example 2 of 2

Adding time, rolling over and measuring gaps

alias is the same object as start, so changing one changed both; copy stayed. 2024 is a leap year, so February 2024 has 29 days and "31 February" rolls over to 2 March.

A Date stores a single moment as the number of milliseconds since 1 January 1970 UTC (a timestamp), and shows it either on the computer's local clock or in UTC. Months count from 0, setters change the object, parsing only works reliably for ISO strings, and the new Temporal API fixes most of these old problems.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write daysBetween(a, b) that takes two ISO date strings like "2024-01-15" and returns the whole number of days between them.

02

Write isWeekend(isoString) that returns true for Saturdays and Sundays, judged in UTC.

03

Write ageOn(birthIso, onIso) that returns a person's age in whole years on a given date.

Explain it without notes

01

What does a Date object actually store?

02

Why do months start at 0, and where does that bite?

03

How should dates be stored in a database or sent in an API, and how should they be displayed?

04

How do you safely add days to a date and count the days between two dates?

Adding time, rolling over and measuring gaps

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

2024-01-15T00:00:00.000Z 2024-01-15T10:30:00.000Z
2024-02-01T00:00:00.000Z
2024-03-02T00:00:00.000Z
29 28
46 true
[ '2024-01-15', '2024-02-01', '2024-03-01' ]
{"at":"2024-03-01T00:00:00.000Z"}