Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timestamps in JavaScript

Tags:

javascript

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?

like image 477
antonjs Avatar asked May 22 '26 23:05

antonjs


1 Answers

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();
like image 121
lonesomeday Avatar answered May 25 '26 09:05

lonesomeday



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!