5.13 Date

The last built-in object we look at in this section is the Date object. JavaScript has many other built-in objects — you will discover more of them as the course goes on — but Date is one you'll use almost daily. Date is a constructor function, so we create dates with the new keyword. It has several overloads.

const now    = new Date();                  // current date and time
const fromStr = new Date("May 15 2022 09:00"); // from a string
const exact  = new Date(2022, 4, 15, 9, 0); // year, month (0-based), day, hour, min

With no argument, new Date() returns the current date and time. With a string, the engine parses common date formats (see MDN's "Date string" section for the list). With numbers, the order is year, month, day, hour, minutes, seconds, milliseconds. Watch out: months are zero-based, so 0 means January and 11 means December — use 4 for May.

Reading and formatting

  • date.getDate(), getFullYear(), getHours(), getMinutes(), getMilliseconds()… — read individual parts.
  • setFullYear(2021), setHours(...), etc. — mutate the date.
  • date.toString() — human-readable, locale-aware string like "Thu Mar 18 2021 ...".
  • date.toTimeString() — only the time component.
  • date.toISOString() — standard ISO format "2021-03-18T09:00:00.000Z".

The ISO format produced by toISOString() is the one you'll use the most when your web or mobile app talks to a backend server, because both sides understand it without ambiguity. That's it for this video on dates — see you in the next one.