tags:

views:

1707

answers:

2

Does anyone know how to parse date string in required format (dd.mm.yyyy)?

+1  A: 

We use this code to check if the string is a valid date

var dt = new Date(txtDate.value)
if (isNaN(dt))
astander
the given format does not match the format required by https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/parse (and thus that Date constructor will not suffice)
Jonathan Fingland
+7  A: 

See https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date and https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/split

var strDate = "03.09.1979";
var dateParts = strDate.split(".");

var date = new Date(dateParts[2], (dateParts[1] - 1) ,dateParts[0]);
Jonathan Fingland
Oops.. a little boo-boo -- the date constructor actually looks like this:new Date(year, month, date [, hour, minute, second, millisecond ])so you need to alter the order of dateParts inside the constructor.
Salman A
@Salman: thanks and quite right. fixed
Jonathan Fingland
Another boo-boo. The JavaScript date constructor is strange in how it handles months. It considers 0 to mean January, 1 to mean February, etc. The line in the code above should look like this:var date = new Date(dateParts[2],dateParts[1] - 1,dateParts[0]);
mikez302
@mikez302, you're right. the linked MDC reference also points that out. code fixed
Jonathan Fingland