我将时间作为Unix时间戳存储在MySQL数据库中,并将其发送给一些JavaScript代码。我怎样才能抽出时间?

例如,HH/MM/SS格式。


当前回答

JavaScript以毫秒为单位工作,因此您必须首先将UNIX时间戳从秒转换为毫秒。

var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...

其他回答

@Aron给出的答案有效,但对我来说不起作用,因为我试图从1980年开始转换时间戳。所以我做了如下几点改变

函数ConvertUnixTimeToDateForLeap(UNIX_Timestamp){var dateObj=新日期(1980,0,1,0,0,2,0);dateObj.setSeconds(dateObj.getSeconds()+UNIX_Timestamp);return dateObj;}document.body.innerHTML=“时间戳:”+ConvertUnixTimeToDateForLeap(1269700200);

所以,如果你有一个从十年左右开始的时间戳,就用这个。这为我省去了很多头疼的事。

上述解决方案的问题是,如果小时、分钟或秒只有一个数字(即0-9),则时间可能是错误的,例如,它可能是2:3:9,但应该是02:03:09。

根据这个页面,使用Date的“toLocaleTimeString”方法似乎是一个更好的解决方案。

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]);

JavaScript以毫秒为单位工作,因此您必须首先将UNIX时间戳从秒转换为毫秒。

var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...