JavaScript provides a comprehensive API for working with dates and times through the Date
object. Here's an in-depth look into JavaScript's date and time capabilities:
You can create a Date
object in several ways:
const now = new Date();
console.log(now); // Current date and time
const specificDate = new Date(2024, 10, 24, 15, 30, 0); // Year, Month (0-based), Day, Hours, Minutes, Seconds
console.log(specificDate);
const fromString = new Date('2024-11-24T15:30:00');
console.log(fromString);
const fromTimestamp = new Date(1732469400000); // Milliseconds
console.log(fromTimestamp);
You can retrieve individual date components using various methods:
const now = new Date();
console.log(now.getFullYear()); // Year (e.g., 2024)
console.log(now.getMonth()); // Month (0-11)
console.log(now.getDate()); // Day of the month (1-31)
console.log(now.getDay()); // Day of the week (0-6, Sunday = 0)
console.log(now.getHours()); // Hours (0-23)
console.log(now.getMinutes()); // Minutes (0-59)
console.log(now.getSeconds()); // Seconds (0-59)
console.log(now.getMilliseconds()); // Milliseconds (0-999)
console.log(now.getTime()); // Timestamp (milliseconds since Jan 1, 1970)
For UTC times: