3

Assuming I have two functions

function newDate(){
  return +new Date();
}
function dateNow(){
  return Date.now();
}

So I wonder if it makes a difference that one returns +new Date() and another Date.now()?

surfmuggle
  • 5,527
  • 7
  • 48
  • 77
c2080584
  • 41
  • 2

2 Answers2

2

According to the spec:

15.9.4.4 Date.now ( )
The now function return a Number value that is the time value designating the UTC date and time of the occurrence of the call to now.

15.9.3.3 new Date ( )
The [[PrimitiveValue]] internal property of the newly constructed object is set to the time value (UTC) identifying the current time.

Coercing the Date object created by new Date() to a number with the unary + operator results in the primitive value. So the question of whether your two cases are always the same boils down to whether the two things below are identical:

  1. date and time of the occurrence of the call to now
  2. the time value identifying the current time

It would seem to be a good bet that they are.

3rd party edit

The chrome (v49) console returns this:

x = Date.now(), y1 = +new Date(), y2 = new Date();
x returns 1463201841680
y1 returns 1463201841680
y2 returns Sat May 14 2016 06:57:21 GMT+0200 
surfmuggle
  • 5,527
  • 7
  • 48
  • 77
1

They give the same value. Verified in chrome devtools console

Date.now() === +new Date()
> true

However, performance is a little better with Date.now()

Performance - Date.now() vs Date.getTime()

Community
  • 1
  • 1
Anthony Chung
  • 1,467
  • 2
  • 22
  • 44