The Date object is a built-in object in JavaScript that allows you to work with dates and times. You can create a new instance of the Date object with or without arguments.
Here are some examples of how to use the Date object:
- Create a new Date object with the current date and time:
let currentDate = new Date();
console.log(currentDate);
- Create a new Date object with a specific date and time:
let specificDate = new Date('March 18, 2023 12:00:00');
console.log(specificDate);
- Get the current year, month, day, and time from a Date object:
let year = currentDate.getFullYear();
let month = currentDate.getMonth();
let day = currentDate.getDate();
let time = currentDate.getTime();
- Format a Date object into a string:
let dateString = currentDate.toDateString();
console.log(dateString);
- Compare two Date objects:
let date1 = new Date('March 18, 2023 12:00:00');
let date2 = new Date('March 18, 2023 15:00:00');
if (date1 < date2) {
console.log('date1 is before date2');
} else {
console.log('date1 is after date2');
}
The Date object has many more methods and properties that you can use to work with dates and times in JavaScript.
