How to get TimeStamp in Javascript?

Question:

I would like to know how I use JavaScript to get the Timestamp ? A number representing the current date and time. I know we got the object for date and time through:

var d = new Date();

But I don't know how to proceed from there.

(Question asked in the beta period of Stack Overflow pt-BR)

Answer:

You can use the Date object's getTime() :

// Pegar do horário atual
var timestamp = new Date().getTime();

// Pegar de uma data específica
var timestamp = new Date(2013, 11, 17).getTime();

But pay attention because this date/time is provided by the client's operating system, if you need some security or the information goes to the base, use some method in your application on the server (back-end).

UPDATE:

An important detail that went unnoticed by me – and it seems that by everyone – is that the month parameter of the Date object's constructor is indexed by zero (zero-indexed), that is, it starts counting from zero, so: 0 = January and 11 = December. In the example above, I used the number 12 to extract today's date (12/17/13) but since December is 11, the result of the example is Fri Jan 17 2014 00:00:00 GMT-0200 (Horário brasileiro de verão) , that is, January , because it moves the date forward – or backward – making the calculation. But that's another story.

Scroll to Top