Dates and time
Dates are needed almost everywhere: a delivery deadline, a birthday, the time of a chat message. In JavaScript, date and time are stored by the built-in Date object. Inside it keeps a single number — how many milliseconds have passed since January 1, 1970 — and its methods turn it into the familiar year, month and day.
The current date
new Date() without arguments creates an object with the current date and time — the moment this line ran:
const now = new Date();
console.log(now.getFullYear() >= 2026); // trueThe result depends on when and where the code runs, so the other examples set the date explicitly.
A specific date
To create a particular date, pass the year, month and day to new Date(). Months are counted from zero: January is 0, December is 11:
const date = new Date(2026, 2, 8);
console.log(date.getDate()); // 8Here 2 is March. You can go on with hours, minutes and seconds: new Date(2026, 2, 8, 14, 30).
Parts of a date
The get... methods return individual parts of a date:
const date = new Date(2026, 2, 8, 14, 30);
console.log(date.getFullYear()); // 2026
console.log(date.getMonth()); // 2
console.log(date.getHours()); // 14
console.log(date.getDay()); // 0getDay() returns the day of the week: 0 is Sunday, 1 is Monday and so on up to 6, Saturday.
Changing a date
The set... methods change a part of a date. If the value goes past the end of the month, the date moves on to the next one by itself:
const date = new Date(2026, 0, 30);
date.setDate(date.getDate() + 5);
console.log(date.getMonth(), date.getDate()); // 1 4Adding 5 days to January 30 gave February 4. This is how deadlines are calculated: "in a week", "in 30 days".
The difference between dates
Subtracting one date from another gives the difference in milliseconds. To turn it into days, divide by the number of milliseconds in a day:
const start = new Date(2026, 2, 1);
const end = new Date(2026, 2, 15);
const days = Math.round((end - start) / (1000 * 60 * 60 * 24));
console.log(days); // 14Math.round() covers daylight saving time changes, when a day can have 23 or 25 hours.
The ISO format
To exchange dates with a server, they are written as a string in ISO format: year, month, day, time and time zone. The toISOString() method turns a date into such a string in UTC, and new Date() can read it:
const date = new Date('2026-03-08T12:00:00Z');
console.log(date.toISOString()); // 2026-03-08T12:00:00.000ZThe Z at the end means UTC, Coordinated Universal Time.
Common mistake
The month in new Date() and getMonth() starts at zero, and it is easy to forget. new Date(2026, 3, 1) is April 1, not March 1:
const date = new Date(2026, 3, 1);
console.log(date.getMonth() + 1); // 4To show the month number to a person, add one, and for nice output use the formatting from the next lesson.