0

I have this code that allows subtract 2 dates in yyyy-mm-dd format to get the days difference. the date that I introduce is date of today ("2018-02-08") minus the date of tomorrow ("2018-02-09") . the result for today should be 1. I want to do it without using any external library. how can I fix it?

var tomorrow = new Date("2018/02/08");
var one_day = 1000 * 60 * 60 * 24;
var today = new Date(); //it is dynamic, depends of the day..
console.log(Math.abs(Math.ceil((today.getTime() - tomorrow.getTime()) / one_day)));
RobG
  • 142,382
  • 31
  • 172
  • 209
yavg
  • 2,761
  • 7
  • 45
  • 115
  • 1
    Your `tomorrow` happened 1 year ago. We're in 2019. – Gerardo Furtado Feb 08 '19 at 04:49
  • Using the built–in parser with a format like "2018/02/08" is unreliable, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results). You need to zero the hours before subtracting, and round the result as not all days are 24 hours long where daylight saving is observed (or use *Date.UTC*). – RobG Feb 08 '19 at 04:51
  • https://stackoverflow.com/a/3224854/2845389 – Kaushik Feb 08 '19 at 04:51

0 Answers0