tags:

views:

1646

answers:

3

I'm having issues parsing dates after 01/01/2000. The results are being returned incorrectly. Basically, 1999 is getting parsed as the year 1999, when it gets to 2000 it is parsing it as 0100, and then 2001 as 0101, etc. Here is the test code to illustrate this issue:

<script type="text/javascript" language="javascript">


// functions incorrect  changes year from 2010 to 0101
var d = (new Date("12/01/2009"));
if (d.getMonth() < 11) 
 { d = new Date(d.getYear(), d.getMonth() + 1, 1); } 
 else
 { d = new Date(d.getYear() + 1, 0, 1); } 
document.write(d);
//  Result:  Sat Jan 01 0101 00:00:00 GMT-0500 (Eastern Standard Time) 

document.write('<br />');


document.write(Date.parse(Date()) < Date.parse(d));
// 
// Result: false  today should definately be < 01/01/2010


document.write('<br />');


// Functions correctly if year is before 2000

var d = (new Date("12/01/1998"));

if (d.getMonth() < 11) 
 { d = new Date(d.getYear(), d.getMonth() + 1, 1); } 
 else
 { d = new Date(d.getYear() + 1, 0, 1); } 


document.write(d);
//  Result:  Fri Jan 01 1999 00:00:00 GMT-0500 (Eastern Standard Time)  
document.write('<br />');


document.write(Date.parse(Date()) < Date.parse(d));
// false


</script>
+4  A: 

You need to use d.getFullYear() instead of d.getYear()

getYear() only gives the number of years since 1900, obviously ;)

Eric Wendelin
Unless you're using IE, in which case getYear() intentionally breaks the standard.
R. Bemrose
Hey, I'm *trying* forget IE :)
Eric Wendelin
A: 

what getYear() returns is browser-dependent. Try d.getFullYear() instead.

A reasonable Javascript date reference: http://www.w3schools.com/jsref/jsref_obj_date.asp

Cameron Pope
+2  A: 

You should be using Date.parse(). Part of why you're seeing odd results is because you use new Date("12/01/2009") up at the top and compare everything else to that. Note that Date.parse() returns a number, not a date object. Therefore, do this for your very first assignment:

var d = new Date(Date.parse("12/01/2009"));

The next part is that you need the getFullYear() function rather than just getYear(), though your problem there is only in your verification code, not in how you actually parse the date.

Joel Coehoorn