JavaScript Dates

Work with dates and times in JavaScript

📅 What are JavaScript Dates?

JavaScript Date objects represent a single moment in time. You can create, format, and manipulate dates and times easily.


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

Output:

Mon Dec 25 2023 10:30:45 GMT-0500 (EST)

Key Date Concepts

🕐

Current Date

Get today's date and time

let today = new Date();
📝

Specific Date

Create a specific date

let birthday = new Date("2023-12-25");
🔢

Get Parts

Extract year, month, day, etc.

today.getFullYear(); // 2023
✏️

Format Date

Display dates in different formats

today.toDateString();

🔹 Creating Dates

Different ways to create Date objects:

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

// Specific date (YYYY-MM-DD)
let christmas = new Date("2023-12-25");

// Date with time (YYYY-MM-DD HH:MM:SS)
let meeting = new Date("2023-12-25 14:30:00");

// Using numbers (year, month, day, hour, minute, second)
// Note: Month is 0-based (0 = January, 11 = December)
let newYear = new Date(2024, 0, 1, 0, 0, 0);

console.log(now);
console.log(christmas);
console.log(meeting);
console.log(newYear);

Output:

Mon Dec 25 2023 10:30:45 GMT-0500 (EST)
Mon Dec 25 2023 00:00:00 GMT-0500 (EST)
Mon Dec 25 2023 14:30:00 GMT-0500 (EST)
Mon Jan 01 2024 00:00:00 GMT-0500 (EST)

🔹 Getting Date Parts

Extract specific parts from a date:

let today = new Date();

console.log("Year:", today.getFullYear());     // 2023
console.log("Month:", today.getMonth());       // 11 (December, 0-based)
console.log("Date:", today.getDate());         // 25
console.log("Day:", today.getDay());           // 1 (Monday, 0=Sunday)
console.log("Hours:", today.getHours());       // 10
console.log("Minutes:", today.getMinutes());   // 30
console.log("Seconds:", today.getSeconds());   // 45

Output:

Year: 2023
Month: 11
Date: 25
Day: 1
Hours: 10
Minutes: 30
Seconds: 45

🔹 Formatting Dates

Display dates in different formats:

let today = new Date();

console.log("Default:", today);
console.log("Date String:", today.toDateString());
console.log("Time String:", today.toTimeString());
console.log("Local String:", today.toLocaleString());
console.log("Local Date:", today.toLocaleDateString());
console.log("Local Time:", today.toLocaleTimeString());

// Custom format
let day = today.getDate();
let month = today.getMonth() + 1; // Add 1 because months are 0-based
let year = today.getFullYear();
console.log("Custom:", month + "/" + day + "/" + year);

Output:

Default: Mon Dec 25 2023 10:30:45 GMT-0500 (EST)
Date String: Mon Dec 25 2023
Time String: 10:30:45 GMT-0500 (EST)
Local String: 12/25/2023, 10:30:45 AM
Local Date: 12/25/2023
Local Time: 10:30:45 AM
Custom: 12/25/2023

🧠 Test Your Knowledge

What does getMonth() return for December?