Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Stupid JavaScript Date inconsistency
- //So, Say you have a string Date
- var lastDayOf2010 = "2010-12-31";
- var choppedLastDayOf2010 = lastDayOf2010.split('-');
- // Let's say you decide to parse the date like so:
- var badDate = new Date(
- choppedLastDayOf2010[0],
- choppedLastDayOf2010[1],
- choppedLastDayOf2010[2]
- );
- //> Mon Jan 31 2011 00:00:00 GMT+0000 (GMT)
- // wtf?
- //
- // Turns out that to pass a month into the new Date()
- // argument, you have to pass in a number between 0
- // (for January) and 11 (for December).
- //
- // So, to get the correct date, I have to do this:
- //
- //
- var correctDate = new Date(
- choppedLastDayOf2010[0],
- choppedLastDayOf2010[1] - 1,
- choppedLastDayOf2010[2]
- );
- //> Fri Dec 31 2010 00:00:00 GMT+0000 (GMT)
- // So you would imagine the same rule would apply to
- // the day (with 0 being the first day of a month),
- // but it doesn't:
- var wtfDate = new Date(
- choppedLastDayOf2010[0],
- choppedLastDayOf2010[1] - 1,
- 0
- );
- //> Tue Nov 30 2010 00:00:00 GMT+0000 (GMT)
- // It seems inconsistent, and is a pain in the ass!
- // Alternatively, you can use the Date.parse() method to
- // convert the lastDayOf2010 string variable into a number
- // representing unix epoch time, and then pass the number
- // into the new Date() code:
- var goodDate = new Date(Date.parse(lastDayOf2010));
- // 2011. Paul Jensen
Add Comment
Please, Sign In to add comment