Difference between Date(dateString) and new Date(dateString)

I have some code that tries to parse a date string.

When I do alert(Date("2010-08-17 12:09:36")); It properly parses the date and everything works fine but I can't call the methods associated with Date, like getMonth().

When I try:

var temp = new Date("2010-08-17 12:09:36");
alert(temp);

I get an "invalid date" error.

Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?


Date()

With this you call a function called Date(). It doesn't accept any arguments and returns a string representing the current date and time.

new Date()

With this you're creating a new instance of Date.

You can use only the following constructors:

new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

So, use 2010-08-17 12:09:36 as parameter to constructor is not allowed.

See w3schools.


EDIT: new Date(dateString) uses one of these formats:

  • "October 13, 1975 11:13:00"
  • "October 13, 1975 11:13"
  • "October 13, 1975"

The following format works in all browsers:

new Date("2010/08/17 12:09:36");

So, to make a yyyy-mm-dd hh:mm:ss formatted date string fully browser compatible you would have to replace dashes with slashes:

var dateString = "2010-08-17 12:09:36";
new Date(dateString.replace(/-/g, "/"));

I know this is old but by far the easier solution is to just use

var temp = new Date("2010-08-17T12:09:36");

The difference is the fact (if I recall from the ECMA documentation) is that Date("xx") does not create (in a sense) a new date object (in fact it is equivalent to calling (new Date("xx").toString()). While new Date("xx") will actually create a new date object.

For More Information:

Look at 15.9.2 of http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf