Come si ottiene un timestamp in JavaScript?

Come posso ottenere un timestamp in JavaScript?

Qualcosa di simile a Unix timestamp, cioè un singolo numero che rappresenta l'ora e la data corrente. Sia come numero che come stringa.

Soluzione

Short & Snazzy:

+ new Date()

Un operatore unario come plus attiva il metodo valueOf nell'oggetto Date e restituisce il timestamp (senza alcuna alterazione).

Dettagli:

Su quasi tutti i browser attuali puoi usare Date.now() per ottenere il timestamp UTC in millisecondi; una notevole eccezione è rappresentata da IE8 e precedenti (vedi tabella di compatibilità).

Puoi facilmente fare uno shim per questo, comunque:

if (!Date.now) {
    Date.now = function() { return new Date().getTime(); }
}

Per ottenere il timestamp in secondi, potete usare:

Math.floor(Date.now() / 1000)

O in alternativa si può usare:

Date.now() / 1000 | 0

Che dovrebbe essere leggermente più veloce, ma anche meno leggibile (anche vedi questa risposta).

Raccomanderei di usare Date.now() (con lo shim di compatibilità). È leggermente meglio perché è più breve e non crea un nuovo oggetto Date. Tuttavia, se non vuoi uno shim & massima compatibilità, potresti usare il metodo "old" per ottenere il timestamp in millisecondi:

new Date().getTime()

Che potete poi convertire in secondi come questo:

Math.round(new Date().getTime()/1000)

E puoi anche usare il metodo valueOf che abbiamo mostrato sopra:

new Date().valueOf()

Timestamp in millisecondi

var timeStampInMs = window.performance && window.performance.now && window.performance.timing && window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now();

console.log(timeStampInMs, Date.now());
Commentari (16)
var time = Date.now || function() {
  return +new Date;
};

time();
Commentari (5)
var timestamp = Number(new Date()); // current time as number
Commentari (0)