3

In order to take the Timestamps in javascript yuo can write this kind of code:

// Usual Way
var d = new Date();
timestamp = d.getTime();

But I found that is it also possible to get the same result in this way:

// The shortest Way
timestamp = +new Date();

Can someone help me to understand how the Shortest Way works?

2 Answers 2

5

That is the unary plus operator. It attempts to convert the argument that follows into a number if it isn't already a number. The Date object implements a method that allows it to be converted to a number, which is the timestamp identical to the getTime() method.


A more legible and obvious way of getting a timestamp without using an extra variable is to use parentheses:

var timestamp = (new Date()).getTime();
Sign up to request clarification or add additional context in comments.

4 Comments

ok, how the unary plus operator works is clear; for example +"1" gives me 1 as a Number; but why +new Date() gives me just the timestamps? I cannot see any timestamp string into Date {Tue Oct 04 2011 13:04:46 GMT+0200 (Romance Daylight Time)}
The timestamp is what is known as the "primitive value" of the Date object. The date is stored internally as the timestamp. When you try to convert an object to a number, the browser gives you that number.
Will it be possible to write a very basic example (an object with a primitive value) that gives the same result when I apply the + operator?
@AntonJs No, but you can do something similar by defining the valueOf method.
0

JavaScript is a dynamic typed language, and it will try conversions appropriate to the context.

When adding a unary plus in front of the Date Object it will be converted to a number.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.