Javascript Date Parsing Bug - Fails For Dates In June (??)
Solution 1:
The problem is that today is July 31.
When you set:
var date = newDate();
Then date.getUTCDate()
is 31. When you set date.setUTCMonth(5)
(for June), you are setting date
to June 31. Because there is no June 31, the JavaScript Date
object turns it into July 1. So immediately after setting calling date.setUTCMonth(5)
if you alert(date.getUTCMonth());
it will be 6
.
This isn't unique to June. Using your function on the 31st of any month for any other month that does not have 31 days will exhibit the same problem. Using your function on the 29th (non-leap years), 30th or 31st of any month for February would also return the wrong result.
Calling setUTC*()
in such a way that any rollovers are overwritten by the correct value should fix this:
var date=newDate();
date.setUTCMilliseconds(0);
date.setUTCSeconds(parseInt(matches[6], 10));
date.setUTCMinutes(parseInt(matches[5], 10) -offset);
date.setUTCHours(parseInt(matches[4], 10));
date.setUTCDate(parseInt(matches[3], 10));
date.setUTCMonth(parseInt(matches[2], 10) -1);
date.setUTCFullYear(parseInt(matches[1], 10));
Solution 2:
The date object starts off with the current date. It's the 31st today so setting 2009-06-09 gives:
var date = newDate(); // Date is 2009-07-31
date.setUTCFullYear(2009); // Date is 2009-07-31
date.setUTCMonth(6 - 1); // Date is 2009-06-31 = 2009-07-01
date.setUTCDate(9); // Date is 2009-07-09
If you set the date to the 1st before you begin, then you should be safe.
Solution 3:
It's because today is July 31. Grant explained the problem. Here's what I believe is a simpler solution. Initialize your date on Jan 1.
var date = newDate(2009,0,1,0,0,0);
Solution 4:
It's the order in which you are changing the date. The date starts out as July 31, so the set of the month fails because there is no 31 in June. (Actually it is rolling over to jul-1.)
After setting the full year, add this:
date.setYUTCDate(1);
It makes it the first of the month wherein every month is valid.
Solution 5:
Looks like a bug?
C:\Documents and Settings\me>java org.mozilla.javascript.tools.shell.Main
Rhino 1.7 release 220090322
js> date = newDate();
Fri Jul 31200915:18:38 GMT-0400 (EDT)
js> date.setUTCMonth(5); date.toUTCString();
Wed, 01 Jul 200919:18:38 GMT
js> date.setUTCMonth(5); date.toUTCString();
Mon, 01 Jun 200919:18:38 GMT
EDIT: Nevermind I guess. Question already answered by somebody more knowledgable.
Post a Comment for "Javascript Date Parsing Bug - Fails For Dates In June (??)"