Date, UTC & calendar arithmetic
Dates without time-zone bugs
Lesson 16 of 20 · 11 min · Module 5: Real-world data
Dates look simple until a user in another time zone sees a deadline one day early. Working with calendar dates in UTC avoids the most common date bugs.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Parse ISO dates as UTC
- Calculate differences in days
- Step through the calendar with UTC methods
The idea
new Date("2026-10-20") is midnight UTC, but getDate() reads local time and can return the 19th. Use the UTC methods: getUTCDay() (0 = Sunday), setUTCDate(), and toISOString().slice(0, 10) for the date part. A day is 86 400 000 milliseconds.
const d = new Date("2026-12-31T00:00:00Z");
d.setUTCDate(d.getUTCDate() + 1);
console.log(d.toISOString().slice(0, 10));
01Local versus UTC
getDate, getDay and setDate use the visitor’s time zone. For calendar logic that must be the same everywhere, use the getUTC… and setUTC… versions.
02Let Date handle the calendar
setUTCDate(32) on a December date rolls into January automatically, and February 29 appears only in leap years. Never add days by hand to the day number.
const d = new Date("2028-02-28T00:00:00Z");
d.setUTCDate(d.getUTCDate() + 1);
console.log(d.toISOString().slice(0, 10));2028-02-2903Round the difference
In time zones with daylight saving time, local midnights can be 23 or 25 hours apart. With UTC dates the difference is exact, and Math.round guards against tiny rounding effects.
Your turn
daysBetween(from, to) for ISO dates like "2026-10-20", returning the number of calendar days from from to to (negative when to is earlier). Write addBusinessDays(date, n) that returns the ISO date n working days (Monday–Friday) later, for n ≥ 0.What the checks look for
- Counts days between dates
- Handles month ends and leap years
- Skips weekends
- Adding zero keeps the date
Take this with you
Treat calendar dates as UTC and convert to local time only for display.
Go a little further
Accept a list of public holidays and skip those days as well.