0

I did not realize the difference between getTime() vs Date.now() in Javascript, both gives the same output ? Is there any difference ?

  • 2
    `Date.now` gives you the milliseconds since January 1, 1970 00:00:00 UTC to the current time, `.getTime` gives you milliseconds elapsed since January 1, 1970 00:00:00 UTC to the date the Date instance has been built on. – Teemu Feb 10 '21 at 06:57
  • 1
    This question is duplicate of this Question/Answer: https://stackoverflow.com/questions/18322583/date-gettime-v-s-date-now – error505 Feb 10 '21 at 07:00

1 Answers1

1

No there should be not difference between the OUTPUT of

new Date().getTime() (without a date string)

and Date.now()

Date.now() The static Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC. (Unix Epoch)


Date.getTime() The getTime() method returns the number of milliseconds since the Unix Epoch.
JavaScript uses milliseconds as the unit of measurement, whereas Unix Time is in seconds.
getTime() always uses UTC for time representation. For example, a client browser in one timezone, getTime() will be the same as a client browser in any other timezone.

console.log(new Date().getTime(),Date.now())

If you add a string or (yyyy,mm-1,dd,hh,min,ss,ms) to the call the new Date() then you will get the number of milliseconds since Epoch to the date you specify:

const d = new Date(2021,1,10,0,0,0,0)
console.log(d.getTime())
const diff = Math.abs(Date.now()-d.getTime()); // difference since 10th of Jan 2021
console.log(new Date(diff).toLocaleTimeString()); // diff WITH timezone offset

For a discussion vs object prototypes and static methods see Date.getTime() v.s. Date.now()

mplungjan
  • 169,008
  • 28
  • 173
  • 236