我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?
例如,HH/MM/SS格式。
当前回答
如果要将Unix持续时间转换为实际的小时、分钟和秒,可以使用以下代码:
var hours = Math.floor(timestamp / 60 / 60);
var minutes = Math.floor((timestamp - hours * 60 * 60) / 60);
var seconds = Math.floor(timestamp - hours * 60 * 60 - minutes * 60 );
var duration = hours + ':' + minutes + ':' + seconds;
其他回答
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)
另一种方式-从ISO 8601日期开始。
var时间戳=1293683278;var date=新日期(时间戳*1000);var iso=date.toISOString().match(/(\d{2}:\d{2})/)警报(iso[1]);
// Format value as two digits 0 => 00, 1 => 01
function twoDigits(value) {
if(value < 10) {
return '0' + value;
}
return value;
}
var date = new Date(unix_timestamp*1000);
// display in format HH:MM:SS
var formattedTime = twoDigits(date.getHours())
+ ':' + twoDigits(date.getMinutes())
+ ':' + twoDigits(date.getSeconds());
Use:
var s = new Date(1504095567183).toLocaleDateString("en-US")
console.log(s)
// expected output "8/30/2017"
时间:
var s = new Date(1504095567183).toLocaleTimeString("en-US")
console.log(s)
// expected output "3:19:27 PM"
请参见Date.protype.toLocaleDateString()
JavaScript以毫秒为单位工作,因此您必须首先将UNIX时间戳从秒转换为毫秒。
var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...