Home > Software engineering >  when substracting two dates in JavaScript it gives me a decimal number, but how is that possible?
when substracting two dates in JavaScript it gives me a decimal number, but how is that possible?

Time:03-27

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:

  1. Get difference between 2 dates in JavaScript?
  2. Get time difference between two dates in seconds
  3. 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 the Date object returns a primitive value, that is either of type number or of type string.

If hint is string or default, [@@toPrimitive]() tries to call the toString method. If the toString property does not exist, it tries to call the valueOf method and if the valueOf does not exist either, [@@toPrimitive]() throws a TypeError.

If hint is number, [@@toPrimitive]() first tries to call valueOf, and if that fails, it calls toString.

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.

  • Related