Home › Learn › JavaScript › Strings and numbers

Dates

Lesson 29 of 40. Create dates, read their parts, and measure between them.

new Date() is now; new Date("2026-03-15") parses an ISO date (as midnight UTC); new Date(2026, 2, 15) builds one from parts, with months counted from zero (2 is March). Getters read the parts: getFullYear(), getMonth() (zero-based), getDate(), getDay() (0 is Sunday). getTime() gives milliseconds since 1970, which is how you do arithmetic: subtract two dates and divide by 86400000 for days.

toISOString() gives the standard 2026-03-15T00:00:00.000Z form; slicing its first ten characters gives a date-only string. Time zones make dates one of the trickier corners of any language; sticking to UTC methods (getUTCDate) avoids off-by-one days near midnight.

const d = new Date("2026-03-15");
console.log(d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate());   // 2026 3 15
const later = new Date("2026-03-20");
console.log((later - d) / 86400000);   // 5

Your task

Write daysBetween(a, b) returning the whole number of days between two ISO date strings (positive when b is later), isoDate(date) returning the YYYY-MM-DD part of a Date, and addDays(iso, n) returning the ISO date n days after the given one.

Part of the final project. addDays works out the delivery date from the order date. It is saved in this browser and loaded into Project: checkout when you get there.

Hint 1

Math.round((new Date(b) - new Date(a)) / 86400000)

Hint 2

date.toISOString().slice(0, 10); addDays: const d = new Date(iso); d.setUTCDate(d.getUTCDate() + n); return isoDate(d);

Show the solution
function daysBetween(a, b) {
  return Math.round((new Date(b) - new Date(a)) / 86400000);
}

function isoDate(date) {
  return date.toISOString().slice(0, 10);
}

function addDays(iso, n) {
  const d = new Date(iso);
  d.setUTCDate(d.getUTCDate() + n);
  return isoDate(d);
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.