Guest User

Untitled

a guest
Jul 19th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. // Stupid JavaScript Date inconsistency
  2.  
  3. //So, Say you have a string Date
  4.  
  5. var lastDayOf2010 = "2010-12-31";
  6. var choppedLastDayOf2010 = lastDayOf2010.split('-');
  7.  
  8. // Let's say you decide to parse the date like so:
  9.  
  10. var badDate = new Date(
  11. choppedLastDayOf2010[0],
  12. choppedLastDayOf2010[1],
  13. choppedLastDayOf2010[2]
  14. );
  15.  
  16. //> Mon Jan 31 2011 00:00:00 GMT+0000 (GMT)
  17.  
  18. // wtf?
  19. //
  20. // Turns out that to pass a month into the new Date()
  21. // argument, you have to pass in a number between 0
  22. // (for January) and 11 (for December).
  23. //
  24. // So, to get the correct date, I have to do this:
  25. //
  26. //
  27.  
  28. var correctDate = new Date(
  29. choppedLastDayOf2010[0],
  30. choppedLastDayOf2010[1] - 1,
  31. choppedLastDayOf2010[2]
  32. );
  33.  
  34. //> Fri Dec 31 2010 00:00:00 GMT+0000 (GMT)
  35.  
  36. // So you would imagine the same rule would apply to
  37. // the day (with 0 being the first day of a month),
  38. // but it doesn't:
  39.  
  40. var wtfDate = new Date(
  41. choppedLastDayOf2010[0],
  42. choppedLastDayOf2010[1] - 1,
  43. 0
  44. );
  45.  
  46. //> Tue Nov 30 2010 00:00:00 GMT+0000 (GMT)
  47.  
  48. // It seems inconsistent, and is a pain in the ass!
  49.  
  50. // Alternatively, you can use the Date.parse() method to
  51. // convert the lastDayOf2010 string variable into a number
  52. // representing unix epoch time, and then pass the number
  53. // into the new Date() code:
  54.  
  55. var goodDate = new Date(Date.parse(lastDayOf2010));
  56.  
  57. // 2011. Paul Jensen
Add Comment
Please, Sign In to add comment