Sto memorizzando il tempo in un database MySQL come timestamp Unix e questo viene inviato a del codice JavaScript. Come potrei ottenere solo il tempo da esso?
Per esempio, nel formato HH/MM/SS.
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
Per maggiori informazioni sull'oggetto Date, si prega di fare riferimento a MDN o alla specifica ECMAScript 5.
JavaScript lavora in millisecondi, quindi dovrete prima convertire il timestamp UNIX da secondi a millisecondi.
var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...
Il timestamp UNIX è il numero di secondi dalle 00:00:00 UTC del 1 gennaio 1970 (secondo Wikipedia).
L'argomento dell'oggetto Date in Javascript è il numero di milisecondi dalle 00:00:00 UTC del 1 gennaio 1970 (secondo la documentazione di W3Schools Javascript).
Vedi il codice qui sotto per un esempio:
function tm(unix_tm) {
var dt = new Date(unix_tm*1000);
document.writeln(dt.getHours() + '/' + dt.getMinutes() + '/' + dt.getSeconds() + ' -- ' + dt + '<br>');
}
tm(60);
tm(86400);
dà:
1/1/0 -- Thu Jan 01 1970 01:01:00 GMT+0100 (Central European Standard Time)
1/0/0 -- Fri Jan 02 1970 01:00:00 GMT+0100 (Central European Standard Time)