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

例如,HH/MM/SS格式。


当前回答

我想使用一个像momentjs.com这样的库,这样做非常简单:

基于Unix时间戳:

var timestamp = moment.unix(1293683278);
console.log( timestamp.format("HH/mm/ss") );

基于MySQL日期字符串:

var now = moment("2010-10-10 12:03:15");
console.log( now.format("HH/mm/ss") );

其他回答

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

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

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)

试试看:

      new Date(1638525320* 1e3).toISOString()  //2021-12-03T09:55:20.000Z

这适用于PHP时间戳

变量d=1541415288860;//var d=值时间戳;//注意:变量名前使用+var date=新日期(+d);console.log(d);console.log(date.toDateString());console.log(date.getFullYear());console.log(date.getMinutes());console.log(date.getSeconds());console.log(date.getHours());console.log(date.toLocaleTimeString());

var d =val.timestamp;
var date=new Date(+d); //NB: use + before variable name

console.log(d);
console.log(date.toDateString());
console.log(date.getFullYear());
console.log(date.getMinutes());
console.log(date.getSeconds());
console.log(date.getHours());
console.log(date.toLocaleTimeString());

上述方法将生成此结果

1541415288860
Mon Nov 05 2018 
2018 
54 
48 
13
1:54:48 PM

有很多方法可以完美地使用时间戳。无法全部列出

现代解决方案(2020年)

在新的世界中,我们应该转向标准的Intl JavaScript对象,该对象具有一个方便的DateTimeFormat构造函数和.format()方法:

函数format_time{const dtFormat=新Intl.DateTimeFormat('en-GB'{timeStyle:'中等',时区:'UTC'});return dtFormat.format(新日期(s*1e3));}console.log(format_time(12345));//"03:25:45"


永恒的解决方案

但为了与所有传统JavaScript引擎100%兼容,这里是将秒格式设置为hh:mm:ss的最短的一行解决方案:

函数format_time{return new Date(s*1e3).toISOString().slice(-13,-5);}console.log(format_time(12345));//"03:25:45"

方法Date.product.toISOString()返回时间简化的扩展ISO 8601格式,总是24或27个字符长(即YYYY-MM-DDTHH:MM:ss.sssZ或分别为±YYYY-MM-DDTHH:MM:ss.sssZ)。时区总是零UTC偏移。

此解决方案不需要任何第三方库,并且在所有浏览器和JavaScript引擎中都受支持。