AI Hints
Home›JavaScript Tutorial›Modules, Dates and Math
JavaScript · Lesson 77 of 138

Dates

Working with time.

⏱ 2 min read▶ Video at 1:33:13🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Birthdays, deadlines, timestamps on messages. Programs work with dates all the time. JavaScript's built in Date object stores a moment in time, and gives you methods to read it.

Dates
From the video: Dates
  • Birthdays, deadlines, timestamps
  • The Date object
  • A moment in time

Making and reading dates

New date with a string creates a specific moment. Get full year and get date read the parts. Watch out, get month counts from zero, so January is zero. Subtracting two dates gives the difference in milliseconds, which we turn into days. Run it.

app.jsjavascript
const launch = new Date("2026-03-15T10:00:00Z");

console.log(launch.toISOString());
console.log(launch.getUTCFullYear(), launch.getUTCMonth(), launch.getUTCDate());

const deadline = new Date("2026-04-01T10:00:00Z");
const days = (deadline - launch) / (1000 * 60 * 60 * 24);
console.log("Days until deadline:", days);
Output
2026-03-15T10:00:00.000Z
2026 2 15
Days until deadline: 17

Dates are tricky

Dates involve time zones, daylight saving, and different formats around the world. Store dates as ISO strings, or as numbers of milliseconds, in UTC. And for showing dates to people, use to locale date string, which formats them for the user's language. For heavy date work, many teams use a library.

keyvalue
new Date(str)a moment
getMonth()starts at 0!
date2 − date1milliseconds
toISOString()a safe format

Summary

The Date object stores moments in time. Remember that months start at zero, and subtracting dates gives milliseconds. Next, the Math object and random numbers.

Key takeaways
  • new Date()
  • Months from 0
  • Subtract for differences
Next up: Math and Random — rounding and chance