In JavaScript, the Date object is used to work with dates and times. It provides methods for creating, formatting, and manipulating dates and times. Here's an overview of how to use Date objects in JavaScript:
You can create a Date object using one of the following methods:
let currentDate = new Date();
let specificDate = new Date('December 17, 1995 03:24:00');
let milliseconds = 1616368800000; // March 21, 2021 12:00:00 UTC
let dateFromMilliseconds = new Date(milliseconds);
You can get various components of a Date object, such as the year, month, day, hours, minutes, seconds, and milliseconds, using the appropriate methods:
let date = new Date();
console.log(date.getFullYear()); // Current year
console.log(date.getMonth()); // Current month (0-11)
console.log(date.getDate()); // Current day of the month (1-31)
console.log(date.getHours()); // Current hour (0-23)
console.log(date.getMinutes()); // Current minute (0-59)
console.log(date.getSeconds()); // Current second (0-59)
console.log(date.getMilliseconds()); // Current millisecond (0-999)
You can format dates into strings using various methods like toDateString() , toTimeString() , toLocaleDateString() , toLocaleTimeString() , toUTCString() , etc.
let date = new Date();
console.log(date.toDateString()); // E.g., "Sat Mar 20 2021"
console.log(date.toTimeString()); // E.g., "17:30:00 GMT+0530 (India Standard Time)"
console.log(date.toLocaleDateString()); // E.g., "3/20/2021"
console.log(date.toLocaleTimeString()); // E.g., "5:30:00 PM"
console.log(date.toUTCString()); // E.g., "Sat, 20 Mar 2021 12:00:00 GMT"
You can manipulate dates using methods like setFullYear() , setMonth() , setDate() , setHours() , setMinutes() , setSeconds() , setMilliseconds() , etc.
let date = new Date();
date.setDate(date.getDate() + 7); // Add 7 days to the current date
You can compare dates using comparison operators (
let date1 = new Date('2021-03-20');
let date2 = new Date('2021-03-21');
if (date1 < date2) {
console.log('date1 is before date2');
} else if (date1 > date2) {
console.log('date1 is after date2');
} else {
console.log('date1 and date2 are equal');
}
JavaScript Date objects are based on the user's local time zone. You can use methods like getTimezoneOffset() to get the time zone offset in minutes and toLocaleString() to format dates based on the user's locale.
Epoch time is the number of milliseconds since January 1, 1970 (Unix Epoch). You can convert a Date object to epoch time using the getTime() method or create a Date object from epoch time using the new Date(milliseconds) constructor.
let date = new Date();
let epochTime = date.getTime();
console.log(epochTime); // E.g., 1616267897600
JavaScript's Date object provides extensive functionality for working with dates and times in your applications. It's essential to understand how to create, manipulate, format, and compare dates to build robust and reliable applications.