views:

90

answers:

4

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()?

A: 

Correct ways to use Date : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

Also, the following piece of code shows how, with a single definition of the function "Animal", it can be a) called directly and b) instantiated by treating it as a constructor function

function Animal(){
    this.abc = 1;
    return 1234; 
}

var x = new Animal();
var y = Animal();

console.log(x); //prints object containing property abc set to value 1
console.log(y); // prints 1234
letronje
A: 

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 equivilent to calling (new Date("xx").toString()). While new Date("xx") will actually create a new date object.

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

Vals
+4  A: 

Date()

With this you call a function called Date(). It accepts date in format "yyyy-mm-dd hh:mm:ss"

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"
Topera
Is there no other way to process the string without creating my own date parser?
Yoshi9143
I don't know how do this using native js. But you can use a external parser, like datejs (http://www.datejs.com/)
Topera
A: 

You're not getting an "invalid date" error. Rather, the value of temp is "Invalid Date".

Is your date string in a valid format? If you're using Firefox, check Date.parse

In Firefox javascript console:

>>> Date.parse("2010-08-17 12:09:36");
NaN
>>> Date.parse("Aug 9, 1995")
807944400000

I would try a different date string format.

Zebi, are you using Internet Explorer?

LarsH