Episode 32 of 46

The Date Object

Learn how to work with dates and times using the built-in Date object.

The Date object is used to work with dates and times in JavaScript.

Creating Dates

// Current date and time
let now = new Date();
console.log(now);

// Specific date
let birthday = new Date("1998-06-15");
let specific = new Date(2024, 0, 15);  // Jan 15, 2024 (months are 0-based!)
let withTime = new Date(2024, 5, 15, 10, 30, 0);  // June 15, 2024 10:30 AM

Getting Date Components

let now = new Date();

now.getFullYear();   // 2024
now.getMonth();      // 0-11 (January = 0!)
now.getDate();       // 1-31 (day of month)
now.getDay();        // 0-6 (Sunday = 0)
now.getHours();      // 0-23
now.getMinutes();    // 0-59
now.getSeconds();    // 0-59
now.getTime();       // Milliseconds since Jan 1, 1970

Formatting Dates

let now = new Date();

now.toLocaleDateString();    // "3/15/2024" (locale-dependent)
now.toLocaleTimeString();    // "10:30:00 AM"
now.toLocaleString();        // "3/15/2024, 10:30:00 AM"
now.toISOString();           // "2024-03-15T10:30:00.000Z"

// Custom format
let formatted = `${now.getDate()}/${now.getMonth() + 1}/${now.getFullYear()}`;
console.log(formatted);  // "15/3/2024"

Date Calculations

// Difference between two dates
let start = new Date("2024-01-01");
let end = new Date("2024-12-31");
let diffMs = end - start;
let diffDays = diffMs / (1000 * 60 * 60 * 24);
console.log(diffDays);  // 365

// Add days to a date
let today = new Date();
today.setDate(today.getDate() + 7);  // One week later