Different ways to create Date
in JavaScript.
Learn about Date
object in JavaScript
To get the current time and date create a Date
object without any arguments.
var now = new Date(); log(now) // Tue Mar 12 2019 21:14:43 GMT+0530 (India Standard Time)
There are many ways of creating a Date object
Passing milliseconds as arguments
If there is single argument and it is of type number then the number is considered as millisecond value.
The milliseconds is counted from the Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)
to check this you can create a Date object passing 0
as argument
// passing millisecondsvar sunDec17 = new Date(819138600000);sunDec17 //Sun Dec 17 1995 00:00:00 GMT+0530 (India Standard Time)___________________________________________________________________passing 0 var date = new Date(0);date // Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)___________________________________________________________________passing negative value will go back from Jan-1-1970var date = new Date(-86,400,000); // -1 day from Jan-1-1970date // Wed Dec 31 1969 05:30:00 GMT+0530 (India Standard Time)
NOTE :To get millisecond of a Date object use DateObj.getTime()
method.
Passing Date String
If you pass a string value then it is considered as DateString.
Example โ2019โ01โ22โ
To learn more about dateString format visit this link
let date = new Date("2019-01-22");date //Tue Jan 22 2019 05:30:00 GMT+0530 (India Standard Time)
Passing all the year, month, date, hours, minutes, seconds, ms
- year should have 4 digit
- if we pass less then 4 digits and that value is less then 100 then it is added to 1900.
- month counts from 0โ11
- date counts from 1โ31(max)
- If date value is not passed or invalid then it takes date value as
1
- If
hours/minutes/seconds/ms
is not passed , then it takes 0 as default value.
var date = new Date(1997, 0, 22);date; // Wed Jan 22 1997 00:00:00 GMT+0530 (India Standard Time)var date = new Date(1997, 0);date; // Wed Jan 01 1997 00:00:00 GMT+0530 (India Standard Time)var date = new Date(97, 0);date; //Wed Jan 01 1997 00:00:00 GMT+0530 (India Standard Time)var date = new Date(107, 2);date; //Tue Mar 01 0107 00:00:00 GMT+0553 (India Standard Time)
if we pass invalid string then it returns invalid date
new Date(undefined) // Invalid Datenew Date(null)
//Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)new Date("hi") // Invalid Datenew Date("") // Invalid Date
Follow Jagathish Saravanan for more interesting posts