I'm watching a video where the diff between two dates returns 10 but when I try it gives me a decimal number but why is that? I could wrap it in Math.floor() but I'd appreciate if anyone explain me. Here is the code
const calcDaysPassed = (date1, date2) =>
Math.abs(date2 - date1) / (1000 * 60 * 60 * 24);
const days1 = calcDaysPassed(
new Date(2037, 3, 4),
new Date(2037, 3, 14)
);
console.log(days1);
CodePudding user response:
Date objects represent a single instant in time and are just a time value that is an offset from 1 Jan 1970 UTC.
The subtraction operator coerces the Date objects to number as if by date.valueOf() which is equivalent to date.getTime(), so when you subtract one date from another you get the difference in their time values such that:
dateA - dateB === dateA.getTime() - dateB.getTime()
So in your code:
new Date(2037, 3, 4) - new Date(2037, 3, 14);
returns the difference in milliseconds:
-864000000
which is 10 standard days.
Note that the values passed to the Date constructor above are interpreted as local so if there is a daylight saving changeover in the date range the difference might be more or less by the amount of the daylight saving shift (typically 1 hour but in some places 30 minutes).
There are lots of similar questions:
- Get difference between 2 dates in JavaScript?
- Get time difference between two dates in seconds
- How to calculate number of days between two dates?
CodePudding user response:
"Date objects contain a Number that represents milliseconds since 1 January 1970 UTC." MDN
date2 - date1 returns the difference in milliseconds. The conversion is described in MDN:
The
[@@toPrimitive]()method of theDateobject returns a primitive value, that is either of typenumberor of typestring.If
hintisstringordefault,[@@toPrimitive]()tries to call thetoStringmethod. If the toString property does not exist, it tries to call thevalueOfmethod and if thevalueOfdoes not exist either,[@@toPrimitive]()throws aTypeError.If
hintisnumber,[@@toPrimitive]()first tries to callvalueOf, and if that fails, it callstoString.JavaScript calls the
[@@toPrimitive]()method to convert an object to a primitive value. You rarely need to invoke the[@@toPrimitive]()method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
Math.abs(date2 - date1) / (1000 * 60 * 60 * 24) converts the milliseconds to days.
