Dates and Time
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Distinguish UTC from local time when reading and writing dates.
- Do date arithmetic in milliseconds instead of mutating fields.
- Format dates for a locale with Intl.DateTimeFormat.
Overview
#The Date object
A Date wraps a single number: milliseconds since the Unix epoch in UTC. The constructor with no arguments uses the current time. A numeric argument is a timestamp, while a string argument is parsed, and parsing strings is inconsistent across formats, so prefer ISO 8601 or explicit numbers.
console.log(new Date(0).toISOString()); // 1970-01-01T00:00:00.000Z
console.log(Date.now() > 0); // true
Local versus UTC
The get and set methods come in local and UTC variants. getMonth returns 0 for January and 11 for December, which is a frequent off-by-one source. getTimezoneOffset reports the local offset in minutes. Storing and transmitting timestamps in UTC and converting only for display avoids a whole class of bugs.
Arithmetic and formatting
Because a Date is a number, subtract two dates to get milliseconds and divide to get days. Mutating methods such as setDate adjust in place, so copy the date first if you need both values. Intl.DateTimeFormat renders a date for a locale and time zone without a helper library.
const days = (a, b) => Math.round((b - a) / 86400000);
console.log(days(new Date('2026-01-01'), new Date('2026-01-11'))); // 10
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this line print?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptconsole.log(new Date(0).getUTCFullYear(), new Date(Date.UTC(2026, 0, 1)).getUTCMonth());Exercise 2Explain
Explain why storing a date as a local string and comparing it to another local string can fail.
starter.textconsole.log(new Date('2026-03-08T02:30:00').toString());Reveal the reference answer
reference.textA local string depends on the machine time zone and can be ambiguous or nonexistent during a daylight saving transition. Two strings that look ordered may not be, and the same instant can produce different strings on different machines. Storing an ISO 8601 UTC string or a numeric timestamp makes comparisons total and unambiguous.Authored expected output: a locale and time-zone dependent string
Local time is a presentation concern. Persisting UTC keeps ordering and equality stable across machines and seasons.
Exercise 3Implement
Implement `daysBetween(start, end)` so it returns the whole number of days between two Date objects. Running `console.log(daysBetween(new Date('2026-01-01'), new Date('2026-01-11')))` should print `10`.
starter.javascriptfunction daysBetween(start, end) { // your code here }Reveal the reference answer
reference.javascriptfunction daysBetween(start, end) { return Math.round((end - start) / 86400000); }Authored expected output: 10
Subtracting two dates yields milliseconds. Dividing by the number of milliseconds in a day and rounding gives a whole-day count that tolerates a daylight saving shift.
Exercise 4Debug
This function should return tomorrow's date without changing the input, but it mutates the caller's Date. Find and fix the bug.
starter.javascriptfunction tomorrow(date) { date.setDate(date.getDate() + 1); return date; } const d = new Date('2026-01-01T00:00:00Z'); const next = tomorrow(d); console.log(d.toISOString(), next.toISOString());Reveal the reference answer
reference.javascriptfunction tomorrow(date) { const next = new Date(date); next.setDate(next.getDate() + 1); return next; } const d = new Date('2026-01-01T00:00:00Z'); const next = tomorrow(d); console.log(d.toISOString(), next.toISOString());Authored expected output: 2026-01-01T00:00:00.000Z 2026-01-02T00:00:00.000Z
setDate mutates the Date it is called on, and the function returns that same object, so the caller's d is changed to tomorrow and both printed values match. Copying the input with new Date(date) first keeps d at January 1 and returns a separate Date for January 2.
Exercise 5Test
Write assertions that prove Date.UTC uses zero-based months and that toISOString is UTC.
starter.javascriptfunction assertEqual(actual, expected, label) { if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual); }Reveal the reference answer
reference.javascriptassertEqual(new Date(Date.UTC(2026, 11, 25)).getUTCMonth(), 11, 'December is month 11'); assertEqual(new Date(0).toISOString(), '1970-01-01T00:00:00.000Z', 'epoch in UTC'); assertEqual(new Date(Date.UTC(2026, 0, 1)).getUTCDate(), 1, 'first of the month'); console.log('all assertions passed');Authored expected output: all assertions passed
The month argument is zero-based, so December is 11. toISOString always renders in UTC with a trailing Z, which makes it safe to persist.
Exercise 6Interview
How would you display a timestamp to users in many time zones?
Reveal the reference answer
reference.textI store the instant as a UTC timestamp and format it at render time with Intl.DateTimeFormat, passing the user time zone and locale. I never bake a local string into storage, and I let the browser resolve the zone when the product does not need an explicit one. For scheduling I keep the zone id alongside the instant so a future change of rules is still correct.The answer should separate storage in UTC from display in a locale and time zone, and should mention Intl rather than manual offset math.
Common misconceptions
#- getMonth returns 1 for January.
- Date string parsing accepts every reasonable format.
- Adding 86400000 milliseconds always advances exactly one calendar day.
Follow-up practice
#- javascript-foundations-json-and-serialization
- javascript-foundations-testing-javascript
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.