How to get TimeStamp in Javascript?

17

Would you like to know how to Javascript to get Timestamp ? A number that represents the current date and time. I know we get the object for date and time through:

var d = new Date();

But I do not know how to proceed from here.

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

    
asked by anonymous 17.12.2013 / 17:39

5 answers

19

You can use the getTime() of the object Date :

// 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 be careful because this date / time is provided by the client operating system, if you need some security or the information is for the base, use some method in your application on the server (backend).

UPDATE:

An important detail that went unnoticed by me - and it seems like by all - is that the month parameter of the constructor of the Date object is indexed by zero (zero-indexed) begins counting from scratch, then: 0 = January and 11 = December. In the example above, I used the number 12 to extract today's date (12/17/13) however as 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 throws the date forward - or backwards - doing the calculation. But that's another story.

    
17.12.2013 / 17:41
4

As everyone said:

new Date().getTime()

Or even more simple:

Date.now()
    
17.12.2013 / 17:44
4

Just to put it another way, besides those mentioned:

+new Date

    
05.02.2014 / 01:38
2

You can use

new Date().getTime();
    
17.12.2013 / 17:41
1

With pure javascript it is possible to get the timestamp like this:

console.log(new Date().getTime());
//ou
alert(new Date().getTime());
    
17.12.2013 / 17:42