The Date object is used to work with dates and times. Date objects are created with a new Date(). We can create a date & time using the following four ways.
new Date()
// Set variable to current date and time
const now = new Date();
console.log(now);
// Output : Fri Mar 25 2022 16:55:26 GMT+0530 (India Standard Time)
new Date(datestring) - The new Date(datestring) constructor creates a date object from a date string.
let d = new Date("2023-01-15");
console.log(d);
// Output : Sun Jan 15 2023 05:30:00 GMT+0530 (India Standard Time)
new Date(milliseconds) - Constructor creates a date object by adding the milliseconds to the zero time. The parameter represents the time passed in milliseconds since 1 January 1970 UTC.
let d1 = new Date(0);
console.log(d1);
//Output : Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)
let d2 = new Date(979875465786);
console.log(d2);
//Output : Fri Jan 19 2001 09:07:45 GMT+0530 (India Standard Time)
new Date(year, month, day, hours, minutes, seconds, milliseconds) - constructor creates a date object with a specified date and time. The seven parameters specify the year, month, day, hours, minutes, seconds, and milliseconds respectively.
let d = new Date(2022, 6, 20, 10, 45, 46, 0);
console.log(d);
//Output : Wed Jul 20 2022 10:45:46 GMT+0530 (India Standard Time)
JavaScript Date Get Methods - You can use the following methods to get information from a date object.
getFullYear() - This method returns the year as a four-digit number (yyyy) according to local time.
let d = new Date();
console.log(d.getFullYear()); //Output : 2022
getMonth() - This method returns the month as a number (0-11) according to local time.
let d = new Date();
console.log(d.getMonth()); //Output : 2
getDate() - This method returns the day as a number (1-31) according to local time.
let d = new Date();
console.log(d.getDate()); //Output : 25
getHours() - This method returns the hour (0-23) according to local time.
let d = new Date();
console.log(d.getHours()); //Output : 17
getMinutes() - This method returns the minute (0-59) according to local time.
let d = new Date();
console.log(d.getMinutes()); //Output : 25
getSeconds() - This method returns the second (0-59) according to local time.
let d = new Date();
console.log(d.getSeconds()); //Output : 40
getMilliseconds() - This method returns the millisecond (0-999) according to local time.
let d = new Date();
console.log(d.getMilliseconds()); //Output : 55