Codectionary / Developer documentation / JavaScript

Date: Creating and Getting Values

The Date object represents a single moment in time. new Date() with no arguments creates the current date/time; it also accepts a specific date, individual components (year, month, day...), or a timestamp. Getter methods like getFullYear(), getMonth(), and getDate() extract individual components - note that getMonth() is zero-indexed (0 = January).

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 2024

Getter 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()); // true

Best 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

Specifications & further reading