What does the plus sign do in '+new Date'

Viewed 49009

I've seen this in a few places

function fn() {
    return +new Date;
}

And I can see that it is returning a timestamp rather than a date object, but I can't find any documentation on what the plus sign is doing.

Can anyone explain?

7 Answers

Here is the specification regarding the "unary add" operator. Hope it helps...

If you remember, when you want to find the time difference between two dates, you simply do as follows:

var d1 = new Date("2000/01/01 00:00:00"); 
var d2 = new Date("2000/01/01 00:00:01");  //one second later

var t = d2 - d1; //will be 1000 (msec) = 1 sec

typeof t; // "number"

Now if you check type of d1-0, it is also a number:

t = new Date() - 0; //numeric value of Date: number of msec's since 1 Jan 1970.
typeof t; // "number"

That + will also convert the Date to Number:

typeof (+new Date()) //"number"

But note that 0 + new Date() will not be treated similarly! It will be concatenated as string:

0 + new Date() // "0Tue Oct 16 05:03:24 PDT 2018"

It does exactly the same thing as:

function(){ return 0+new Date; }

that has the same result as:

function(){ return new Date().getTime(); }
Related