Syntax
new Date()
date.getFullYear()
date.getMonth()Examples
Creating Dates
Different ways to construct a Date object.
const now = new Date(); // current date and time
const specific = new Date(2024, 5, 15); // June 15, 2024 - month is 0-indexed!
const fromString = new Date("2024-06-15");
const fromTimestamp = new Date(1718409600000); // milliseconds since Jan 1, 1970
console.log(specific); // June 15 2024Getter Methods
Extracting individual components from a Date object.
const date = new Date(2024, 5, 15); // June 15, 2024
console.log(date.getFullYear()); // 2024
console.log(date.getMonth()); // 5 - remember, 0-indexed! (0=Jan, 5=Jun)
console.log(date.getDate()); // 15 - day of the month
console.log(date.getDay()); // day of the week (0=Sunday, 6=Saturday)
console.log(date.getHours()); // hour (0-23)Date.now() and Timestamps
Getting the current timestamp for calculations, like measuring elapsed time.
const start = Date.now(); // current timestamp in milliseconds
// ... some operation happens ...
const end = Date.now();
console.log(`Took ${end - start}ms`);
// Comparing two dates by their timestamps
const date1 = new Date(2024, 0, 1);
const date2 = new Date(2024, 5, 1);
console.log(date2.getTime() > date1.getTime()); // trueBest practices
- Remember getMonth() is zero-indexed (January is 0, December is 11) - a very common source of off-by-one bugs
- Use Date.now() rather than new Date().getTime() when you just need the current timestamp for comparisons or performance measurement
- Prefer ISO 8601 format ("2024-06-15") when creating dates from strings, since other formats can be parsed inconsistently across browsers
- For serious date manipulation (time zones, formatting, arithmetic), consider a dedicated library or the newer Temporal API rather than hand-rolling logic with the legacy Date object
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification