This article is first published on hackinbits.com
new Date() new Date(milliseconds) new Date(date string) new Date(year, month, date, hours, minutes, seconds, milliseconds)
new Date() without any arguments will return the current date-time.
let date = new Date(); console.log(date); //return current date-time // format: Thu May 14 2020 00:41:03 GMT+0530 (India Standard Time)
new Date(milliseconds) creates a Date object with date-time equal to the total number of milliseconds elapsed since 1st January 1970 UTC+0.
The time elapsed in milliseconds from 1st January 1970 is known as a timestamp.
let unixEpoch = new Date(0); console.log(unixEpoch); // Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time) let unixEpochAnd2Days = new Date(2 * 24 * 3600 * 1000); console.log(unixEpochAnd2Days); // Sat Jan 03 1970 05:30:00 GMT+0530 (India Standard Time)
To create a Date object with a date earlier than 1st January 1970, we pass negative timestamp to the Date constructor.
let ADayBeforeUnixEpoch = new Date(- 24 * 3600 * 1000); console.log(ADayBeforeUnixEpoch); // Wed Dec 31 1969 05:30:00 GMT+0530 (India Standard Time)
You can create a Date object for a given year, month, and other parameters using Date constructor. The first two parameters are mandatory.
let date = new Date(2019, 00, 30, 01, 01, 01, 0); console.log(date); // Wed Jan 30 2019 01:01:01 GMT+0530 (India Standard Time) let date = new Date(2019, 00) console.log(date) // Tue Jan 01 2019 00:00:00 GMT+0530 (India Standard Time)
If you have passed only one parameter, Date object will take it as milliseconds.
- year: year must have 4 digits, for example, 2016.
- date: date of the month, if not provided, default is set to 1.
- Defaults for all other parameters: hours, minutes, seconds, and milliseconds are taken as 0 if not provided.
new Date(date string) creates a Date object from the date string.
We will discuss the date string in detail in the next article.
Let's practice what you have learned above.
- Create a date object with the date equal to one week hence 1st January 1970.
- Create a date object with the date equal to one week before 1st January 1970.
Let us know your answers in the comments. Have a nice day.