tags:

views:

90

answers:

6

I have astring directly coming form the database and I am creating object of Date as
Date dt=Date("23.03.2010") and it is comin NaN

whereas when I use Date dt= Date("03/23/2010") it works fine.

Any Idea how I can get this working?.

+2  A: 

You must pass string (parsed) dates in MDY format. This is to prevent ambiguity (does 5/6/2010 mean 6th May or 5th June?)

If you prefer, you can use new Date(year, month, day) format, and pass the arguments separately.

rjh
that should be `6th May or 5th june` .. :)
Gaby
I always find it funny that `m/d/y` should prevent ambiguity as it's only used in a pretty minuscule part of the world; I'd say most people would find it more confusing than ISO 8601 ;-)
Joey
I'm from the UK, I agree wholeheartedly :) d/m/y would be sensible, and y/m/d the least ambiguous.
rjh
+1  A: 

The safest way if is you can return the date as milliseconds since 1970-01-01, then you can easily create a Date object from it. Example:

var n = 1269302400000;
var dt = new Date(n);
Guffa
Not very human-readable, then, though.
Joey
A: 

Note that you'll want to invoke Date with the new operator - from the Mozilla Developer Center:

Invoking Date in a non-constructor context (i.e., without the new operator) will return a string representing the current time.

The same page details the syntax of the Date constructor.

If you are constructing a Date from a string the format accepted is governed by the rules of the Date.parse method. See Microsoft's Date.parse documentation for a summary of these rules.

Simon Lieschke
A: 

try

d="23.03.2010".split(".");
Date dt=Date([d[1],d[0],d[2]].join("/"))

i think it isn't the most beautiful way.

Falcon
A: 

Give this a try...

var dateParts = '23.03.2010'.split('.');
// -1 from month because javascript months are 0-based
var dateObj = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
Craig
That would give you a Date object with the month april, not march.
Guffa
The month will be off by one since the second argument to the `Date` constructor is a number in the range 0-11.
Martin Liversage
@Martin: really? JavaScript has the same braindead API as Java in that respect?
Joachim Sauer
+1  A: 

You can parse the string from the database and then create the date object. You will have to subtract 1 from the parsed month value to get a correct date.

var dateString = "23.03.2010";
var dateParts = dateString.split(".");
var dt = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
Martin Liversage