我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
当前回答
我偏爱JacobWright的Date.format()库,它以PHP的Date()函数的风格实现JavaScript日期格式。
new Date(unix_timestamp * 1000).format('h:i:s')
其他回答
UNIX时间戳是自1970年1月1日00:00:00 UTC以来的秒数(根据维基百科)。
Javascript中Date对象的参数是自1970年1月1日00:00:00 UTC以来的毫秒数(根据W3Schools Javascript文档)。
例如,请参见以下代码:
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);
给予:
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)
将秒格式设置为hh:mm:ss:variant的最短一行解决方案:
console.log(新日期(1549312452*1000).toISOString().slice(0,19).replace('T',''));// "2019-02-04 20:34:12"
另一种方式-从ISO 8601日期开始。
var时间戳=1293683278;var date=新日期(时间戳*1000);var iso=date.toISOString().match(/(\d{2}:\d{2})/)警报(iso[1]);
function timeConverter(UNIX_timestamp){
var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();
var time = hour+':'+min+':'+sec ;
return time;
}
上述解决方案的问题是,如果小时、分钟或秒只有一个数字(即0-9),则时间可能是错误的,例如,它可能是2:3:9,但应该是02:03:09。
根据这个页面,使用Date的“toLocaleTimeString”方法似乎是一个更好的解决方案。