Date vs new Date in JavaScript
new Date()
takes an ordinal and returns a Date
object.
What does Date()
do, and how come it gives a different time?
>>> new Date(1329429600000)
Date {Fri Feb 17 2012 00:00:00 GMT+0200 (القدس Standard Time)}
>>> Date(1329429600000)
"Tue Mar 06 2012 15:29:58 GMT+0200 (Jerusalem Standard Time)"
From the specs:
When
Date
is called as a function rather than as a constructor, it returns a String representing the current time (UTC).
and:
When
Date
is called as part of anew
expression, it is a constructor: it initialises the newly created object.
So, new Date(...)
returns an object such that obj instanceof Date
is true, whereas Date(...)
basically returns the same as new Date().toString()
.
new Date
creates a new Date object that you can modify or initialize with a different date while Date
returns a string of the current date/time, ignoring its arguments.
Check out JavaScript Date for a quick API reference and code test bed. You can see the Date()
function called without new
does not take any parameters and always returns a string
representation of the current date/time. If you modify the sample to be:
console.log(Date());
console.log(Date(1329429600000));
You'll find the results for both are the same (because JavaScript ignores extra arguments passed to functions):
Wed Apr 11 2012 09:58:11 GMT-0700 (PDT)
Wed Apr 11 2012 09:58:11 GMT-0700 (PDT)