Ik sla de tijd op in een MySQL database als een Unix tijdstempel en dat wordt naar wat JavaScript code gestuurd. Hoe krijg ik daar alleen de tijd uit?
Bijvoorbeeld, in HH/MM/SS formaat.
// 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);
Voor meer informatie over het Date object, raadpleeg MDN of de ECMAScript 5 specificatie.
JavaScript werkt in milliseconden, dus moet je eerst de UNIX-tijdstempel omzetten van seconden naar milliseconden.
var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...
UNIX timestamp is aantal seconden sinds 00:00:00 UTC op 1 januari 1970 (volgens Wikipedia).
Argument van Date object in Javascript is aantal miliseconden sinds 00:00:00 UTC op 1 januari 1970 (volgens W3Schools Javascript documentatie).
Zie onderstaande code voor een voorbeeld:
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);
geeft:
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)