JavaScript Date constructor is used to create a new Date object. The value returned will be different on the basis of whether the object is called with or without the new keyword. If we call the object new keyword a Date object is created otherwise a string representing the current dat-time is returned. Also, if we use this constructor as a function it will return a string containing the present date-time.
Syntax:
new Date(val)
new Date(DateStr)
new Date(DateObj)
new Date(year, monthIndex, day, hours, minutes, seconds, ms
)
Parameters: The date object can be created with or without any parameter
- val: This is the value of date in Integer format representing the time in milliseconds since Jan,1,1970
- DateStr: This is the date in String format valid in Date.parse() method.
- DateObj: This is the date object itself passed as a parameter
Other parameters such as year, mothIndex, day, hours, minutes, second, and ms are optional and are integer values representing the specified year, month, day, hours, minutes, seconds, or milliseconds respectively.
Note: If we do not pass any parameter then the date at which the object is created is stored in the object.
a Example 1: In this example, we will create a date using different parameters.
Javascript
const date1 = new Date(); const date2 = new Date(500); const date3 = new Date( "12-03-2022" ); const date4 = new Date(date1); console.log(date1); console.log(date2); console.log(date3); console.log(date4); |
2023-05-15T10:13:23.764Z 1970-01-01T00:00:00.500Z 2022-12-03T00:00:00.000Z 2023-05-15T10:13:23.764Z
Example 2: In this example, we will pass values other than string, integer or date object.
Javascript
const date1 = new Date(undefined); const date2 = new Date( null ); console.log(date1); console.log(date2); |
Output: Since undefined is a primitive data type it is converted to NaN but null is converted to zero.
Invalid Date
Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)
Example 3: In this example, we will pass the array as a parameter.
Javascript
const date1 = new Date([ "2020-06-03" , "12:10" ]); console.log(date1); |
Output: Array is converted to a string and is taken as a string input then converted to Date. This method will not work in Firefox
Wed Jun 03 2020 12:10:00 GMT+0530 (India Standard Time)
Supported Browser:
- Chrome
- Edge
- Firefox
- Opera
- Safari