Home > Mobile >  Difference between Date.now(), new Date().getTime(), and new Date
Difference between Date.now(), new Date().getTime(), and new Date

Time:09-28

I usually use Date.now() to get a timestamp. But lately I had to construct a Date object and learn all the methods. I found that .getTime() returns the same thing as Date.now(). So then whats the point of getTime()? Also, why does this work new Date <-- no () after Date and before new. And why does it ALSO return the timestamp?

CodePudding user response:

Date.now() gives you the timestamp right now.

Date.getTime() gives you the timestamp of a date object that may represent a moment in the past or future.

new Date is a slightly confusing way of saying "create a new Date object, then convert it to a number" (identical to new Number(new Date()), and when you convert a Date to a number, it returns the date's timestamp (i.e. getTime().

Use #1 if you want the timestamp right this second, and use #2 if you want to get the timestamp of a Date object you got from somewhere else. Don't use #3 ever - it might look clever, but all you're doing is writing code that's going to confuse yourself or someone else later.

(Side point, the reason new Date works is because you don't actually need parentheses to create an object if you are passing no parameters. You should still use empty parameters though for readability if nothing else.)

CodePudding user response:

Like this post already explained (Performance - Date.now() vs Date.getTime()), the difference between Date.now() and Date.getTime() are mostly just performance, one comment also states that 'Date.now() doesn’t work in Internet Explorer versions earlier than IE9'.

The method with the unary plus operator, so Date.now works because the unary plus operator trys to convert something to a number. You can achiev the same with using Number(new Date). The parentheses are not necessary because you are not passing any arguments.

See here for more information on why this works that way: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive

  • Related