0

I'm trying to get the number of days between the current date and a specific date in JavaScript and I'm experiencing a weird behavior with Date(). The output that I get from this code is 32, but if today is Aug 28 and the specified date is Aug 30 I should/would like to get 2 as the output. Any suggestions? Thanks.

// hours*minutes*seconds*milliseconds
    const oneDay = 24 * 60 * 60 * 1000;

    const firstDate = new Date(2020, 8, 30);
    const secondDate = new Date();

    const diffDays = (firstDate - secondDate) / oneDay;

    document.write(Math.round(diffDays));
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Chris Faux
  • 145
  • 9
  • 1
    Aug: `new Date(2020, 7, 30)` – Aks Jacoves Aug 28 '20 at 19:45
  • 1
    a few things. one - the param formatting for the new Date() is wrong, instead of , use - two. the diffDays. you want to use Math.abs() to get an absolute difference of value. three. instead of rounding. you probably want ceil to get the difference in days inclusive instead of exclusive. ``` // hours*minutes*seconds*milliseconds const oneDay = 24 * 60 * 60 * 1000; const firstDate = new Date("2020-8-30"); const secondDate = new Date(); const diffDays = Math.abs((firstDate-secondDate) / oneDay); document.write(Math.ceil(diffDays)); ``` – altruios Aug 28 '20 at 19:53
  • the comment from altruios solved this issue. Thanks a lot. – Chris Faux Aug 28 '20 at 20:08
  • // FINAL CODE const oneDay = 24 * 60 * 60 * 1000; const firstDate = new Date("2020-8-30"); const secondDate = new Date(); const diffDays = Math.abs((firstDate - secondDate) / oneDay); document.write(Math.ceil(diffDays)); – Chris Faux Aug 28 '20 at 20:09
  • Note that not all days are 24 hours long where daylight saving is observed. – RobG Aug 29 '20 at 01:07

1 Answers1

1

This is because the month parameter is ranging from 0 to 11. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date

CC.
  • 464
  • 4
  • 11