HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Dates

JavaScript Date objects allow us to work with dates. Dates are static by default. The computer time is not moving in a Date object, it represents a single moment in time.


Creating Date Objects

You can create a new Date object using the new Date() constructor. There are 4 ways to create a new date:

// 1. Current date and time
const d1 = new Date();

// 2. From a date string
const d2 = new Date("2022-03-25");

// 3. From specific numbers (year, month, day, hours, minutes, seconds, ms)
const d3 = new Date(2022, 11, 24, 10, 33, 30, 0);

// 4. From milliseconds (since Jan 01, 1970)
const d4 = new Date(1000000000000);
Important: JavaScript counts months from 0 to 11. January is 0, and December is 11.

Displaying Dates

JavaScript will (by default) output dates in full text string format:

const d = new Date();
console.log(d.toString()); // Full format

Common Output Methods:

  • toDateString(): Returns a readable date (e.g., "Fri Mar 25 2022").
  • toUTCString(): Converts a date to a UTC string (GMT format).
  • toISOString(): Returns the date in standard ISO format.

Quick Reference: Date Constructors

Syntax Description
new Date() Creates a date object with the current date and time
new Date(year, month, ...) Creates a date object with a specified date and time
new Date(milliseconds) Creates a date object as zero time plus milliseconds
new Date(date string) Creates a date object from a date string

Key Points to Remember

  • The Date object is static once created
  • Months are 0-indexed (0 = Jan, 11 = Dec)
  • Creating a date with only 2 digits for year (e.g., 99) will be interpreted as 19xx (e.g., 1999)
  • Dates are stored in milliseconds since Jan 1, 1970
  • Always use new Date() to create date instances
  • Formatting dates is easier with built-in methods like toDateString()