JavaScript Date Arithmetic: Durations and Calendar Days
Quick answer
Adding a fixed duration to a timestamp is different from advancing a local calendar date. Daylight-saving changes can make a local calendar day shorter or longer than 24 hours.
How it works
For elapsed time, subtract millisecond time values. Date setters mutate the instance and return its new time value. setUTCDate(getUTCDate()+1) advances a UTC calendar day; setDate uses local fields. Months have variable lengths and setters normalize overflow. Decide whether the requirement is elapsed duration, a calendar day or a local appointment; choose an explicit time zone for presentation.
const a=Date.parse("2024-03-30T12:00:00+01:00"); const b=Date.parse("2024-03-31T12:00:00+02:00"); console.log((b-a)/3600000);Expected output in Node.js:
23The clock labels differ by a day, while the offset advances by one hour.
const d=new Date("2024-02-28T00:00:00Z"); d.setUTCDate(d.getUTCDate()+2); console.log(d.toISOString());Expected output in Node.js:
2024-03-01T00:00:00.000ZThe leap day is traversed and overflow advances to March.
Common mistakes
Adding 86,400,000 milliseconds is not a universal way to schedule the same local clock time tomorrow. Also, setUTCMonth on the 31st may normalize into a later month.
Practice
Compare elapsed hours between two explicit offset timestamps across a spring offset change, and explain why it is not 24.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Date Arithmetic: Durations and Calendar Days — Knowledge Check
Apply the taught concept and predict the output.
What does Date.setUTCDate return?
Why can two local noons on consecutive dates differ by 23 hours?
Which operation measures elapsed milliseconds between valid Date values a and b?
What is the exact console output in JavaScript Date Arithmetic: Durations and Calendar Days example 1?
const a=Date.parse("2024-03-30T12:00:00+01:00"); const b=Date.parse("2024-03-31T12:00:00+02:00"); console.log((b-a)/3600000);What is the exact console output in JavaScript Date Arithmetic: Durations and Calendar Days example 2?
const d=new Date("2024-02-28T00:00:00Z"); d.setUTCDate(d.getUTCDate()+2); console.log(d.toISOString());