'date time in javascript [duplicate]
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?
Solution 1:[1]
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);
Solution 2:[2]
Convert to Millisecond and then perform same logic
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | MITESH KR JHA |
