JavaScript Date

The Date object stores a date and time.

const now = new Date();                  // current date and time
const d1 = new Date("2025-01-15");        // from text
const d2 = new Date(2025, 0, 15);         // year, month (0-11), day
const d3 = new Date(0);                   // milliseconds from 1 Jan 1970
Note: Months start from 0: January is 0 and December is 11. This surprises everybody.

Get parts of a date

const d = new Date("2025-01-15T10:30:00Z");

console.log(d.getUTCFullYear());
console.log(d.getUTCMonth());
console.log(d.getUTCDate());
console.log(d.getUTCDay());
console.log(d.toISOString());
Output of the above program is

2025
0
15
3
2025-01-15T10:30:00.000Z

The getUTC... methods use UTC time. The normal ones (getFullYear(), getMonth(), getDate(), getDay(), getHours()) use the visitor’s local time zone. getDay() gives 0 for Sunday, so 3 here is Wednesday.


Change a date

const d = new Date(2025, 0, 31);
d.setDate(d.getDate() + 1);   // add one day
console.log(d.getMonth(), d.getDate());
Output of the above program is

1 1

JavaScript fixes the date by itself: 31 January plus one day is 1 February (month 1, day 1).


Compare dates and find the difference

const a = new Date("2025-01-01");
const b = new Date("2025-01-11");

console.log(a < b);
const days = (b - a) / (1000 * 60 * 60 * 24);
console.log(days);
Output of the above program is

true
10


Format a date for display

const d = new Date("2025-01-15T10:30:00Z");

console.log(d.toLocaleDateString("en-IN", { timeZone: "UTC" }));
console.log(d.toLocaleDateString("en-US", { timeZone: "UTC", year: "numeric", month: "long", day: "numeric" }));
Output of the above program is

15/1/2025
January 15, 2025

Note: Date and time zones are tricky. For complex work you can use a library like date-fns. The current time in milliseconds is Date.now().

Summary

  • Create dates with new Date().
  • Months start at 0.
  • Subtract two dates to get milliseconds.
  • Format with toLocaleDateString().
  • Next: Error Handling.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.