Today I found a very weird bug in JavaScript – The date function. I never expected to see a bug in the standard JavaScript implementation. Here is my code. It does nothing more than adding 21 days on the reference date:
var referenceDateObject = new Date(2011, 9, 10); var deliveryDateObj = new Date(referenceDateObject.getTime() + 24 * 60 * 60 * 1000 * 21); var deliveryDateMonth = parseInt(deliveryDateObj.getUTCMonth()); var deliveryDateString = deliveryDateObj.getUTCFullYear() + '-' + deliveryDateMonth + '-' + deliveryDateObj.getUTCDate(); alert(deliveryDateString);
Given a reference date of September 10, 2011, I expect the date should be October 1, 2011. However, it ends up returning me September 31, which doesn’t exist!
I test that on Firefox and Google Chrome, both give the same problem. A quick fix will be moving the date calculation to the server side.
P.S. MySQL date function automatically convert 9/31 to 10/1, so the data on the server looks fine.
Update – That’s my fault. The Date object treats the month from 0-11 instead of 1-12. Here is a corrected version:
var referenceDateObject = new Date(2011, 8, 10); //That's September 10, 2011, not August 10. var deliveryDateObj = new Date(referenceDateObject.getTime() + 24 * 60 * 60 * 1000 * 21); var deliveryDateMonth = parseInt(deliveryDateObj.getUTCMonth()) + 1; var deliveryDateString = deliveryDateObj.getUTCFullYear() + '-' + deliveryDateMonth + '-' + deliveryDateObj.getUTCDate(); alert(deliveryDateString);
That will do the trick.
–Derrick
Our sponsors: