Updated March 18, 2023
To define a new Date object, we need to call a new Date() with one of the following options:
new Date(year, month index [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
We need to use the new operator to instantiate a Date object. If we use the Date object directly, such as now = Date(), the returned value is a string rather than a Date object.
Let us see with the help of some examples below:
Example #1 – Display Current Date and Time
<!DOCTYPE html> <html> <body> <h2>JS Dates</h2> <p id="display"></p> </body> <script> var current_date = new Date(); document.getElementById("display").innerHTML = current_date; </script> </html>
- ISO Date (International Standard) – “2019-11-06”
- Long Date – “Nov 12, 2019” or “12 Nov 2019”
- Short Date – “12/11/2019”
Example #2 – Display Dates in Various Formats
<!DOCTYPE html> <html> <body> <h2>JS Dates</h2> </body> <script> const months = ["JAN", "FEB", "MAR","APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; var current_date = new Date(); console.log("ISO Format: " ,current_date.getFullYear()+"-"+current_date.getMonth()+"-"+current_date.getDate()) console.log("Long Format: " ,current_date.getDate()+" "+months[current_date.getMonth()]+" "+current_date.getFullYear()) console.log("Short Format: " ,current_date.getDate()+"-"+current_date.getMonth()+"-"+current_date.getFullYear()) </script> </html>
From the above code, we can see that the Month part of the date starts from zero i.e. January is the zeroth month. The same goes for the daypart as well (getDay()), Sunday starts from zero.
Example#3 – Wrong Date Displayed
<!DOCTYPE html> <html> <body> <h2>JS Dates</h2> <p id="display"></p> </body> <script> var current_date = new Date('12-11-2019'); document.getElementById("display").innerHTML = current_date; </script> </html>
Now, we will display date-time in milliseconds using Date.parse() function. This function gets the exact number of milliseconds that have passed since midnight, January 1, 1970, until the date that has been provided.
Example #4 – Date in Milliseconds
<!DOCTYPE html> <html> <script> var msec_date = Date.parse('12-11-2019'); console.log("Date in Milli-Seconds:", msec_date) </script> </html>
Example #5 – Auto-Correction of Date Value
<!DOCTYPE html> <html> <script> var autocorrect_date = new Date(2019,9,46); console.log("Date Value:", autocorrect_date) </script> </html>
The above code example recalculates the value provided and displays a correct, acceptable date value. Also, if we notice the code section of how the data value is provided, it seems that we can break up the date and time value part and present it as individual numbers separated by a comma. The value “9” represents the month of October, as discussed in the earlier section of this article, that the Month part of the date starts from 0 (January =0, February=1, and so on..)