Home > other >  Why does Date.now - a given date work? Documentation shows that Date.now() returns the ms since 1970
Why does Date.now - a given date work? Documentation shows that Date.now() returns the ms since 1970

Time:12-20

const daysFromNow = (date) => Math.round((date-Date.now())/(1000*3600*24))

console.log(daysFromNow(new Date('07/04/2020'))); 

//result is -534 

Given the above, why does it work? I've read that .now() gives back the ms since 1970. Does the passed in date hold a value of the ms since 1970 as well?

CodePudding user response:

Does the passed in date hold a value of the ms since 1970 as well?

The Date object represents a specific moment on earth, so yes you can retrieve that the milliseconds since 1970 in milliseconds.

A Date object has a valueOf function that returns the primitive value of the Date:

The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date.

So (new Date()).valueOf() and Date.now() are equivalent:

console.log((new Date()).valueOf())
console.log(Date.now())

And the valueOf is called for conversion in the case of date - Date.now() because date is a Date object and Date.now() returns a number.

Here an example of a custom object with a valueOf function:

let test = {
  valueOf() {
    return 5;
  }
}

console.log(test - 1);

CodePudding user response:

That's work because of valueOf property. That property return a number, implemented in all objects in js. You can also owerride it in your objects.

Here an example of using for creating add chain js function.

function add(x) {
  const fn = (y) => add(x   y);
  fn.valueOf = () => x;
  return fn;
}

const addTen = add(5)(5);

console.log(addTen   1) // 11

  • Related