-1

I have a code script to calculate the number of days between today and an expected day:

let date1 = new Date(); //today
let date = new Date("04/19/2022") //expected day
let differenceInTime = date1.getTime() - date.getTime(); //difference by milliseconds
let differenceInDay = (differenceInTime - differenceInTime%(1000 * 3600 * 24))/(1000 * 3600 * 24); // JS does not supports dividing by whole so I implement this to get the number of days

The result is true for every cases, except that when I choose the day after today (tomorrow) as expected day, the result also is 0. Is there something not exact in my code?

Duy Duy
  • 521
  • 1
  • 4
  • 9

2 Answers2

0

the problem with your code is that on line 4 you kinda fix the differenceInTime to 0 decimals and difference between the expected day and today is less than 1 in days, so It'll be truncated.


You can do it easier this way. using Math methods or num.toFixed() your code will be shorter and cleaner.

you don't even need date.getTime() cause date will automatically convert to ms when you do mathematical operations on it.

let date1 = new Date(); //today
let date = new Date("04/20/2022"); //expected day
let differenceInMS = date1 - date; //difference in ms
let differenceInDay = (differenceInMS / 8.64e7).toFixed(1); // 8.64e+7 : a day in ms
console.log(differenceInDay);
Rocky
  • 117
  • 1
  • 1
  • 9
  • It doesn't give true result, having .5 decimal – Duy Duy Apr 19 '22 at 05:40
  • @DuyDuy I assumed you want the answer in decimals your 4th line already acts as`differenceInMS.toFixed()` the reason you are getting zero is because the difference of now with tomorrow by the code you provided is less than 24 hours in ms. and It's thrown away when you write this: `(differenceInMS - differenceInMS % 8.64e7)/ 8.64e7;` which is almost equal to `differenceInMS.toFixed();` – Rocky Apr 19 '22 at 06:15
-2

Convert to Millisecond and then perform same logic