Čas shranjujem v podatkovno zbirko MySQL kot časovni žig Unix, ki se pošlje kodi JavaScript. Kako bi iz nje dobil samo čas?
Na primer v obliki 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);
Več informacij o objektu Date najdete v MDN ali specifikaciji ECMAScript 5.
JavaScript deluje v milisekundah, zato boste morali najprej pretvoriti časovni žig UNIX iz sekund v milisekunde.
var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...
Časovni žig UNIX je število sekund od 00:00:00 UTC 1. januarja 1970 (po Wikipediji).
Argument predmeta Date v javascriptu je število milisekund od 00:00:00 UTC 1. januarja 1970 (po W3Schools Javascript documentation).
Za primer glejte spodnjo kodo:
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);
daje:
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)