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

例如,HH/MM/SS格式。


当前回答

这适用于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

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

其他回答

最短的

(new Date(ts*1000)+'').slice(16,24)

设ts=1549312452;让时间=(新日期(ts*1000)+“”).切片(16,24);console.log(时间);

现代解决方案(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引擎中都受支持。

您可以使用以下格式(源代码):

const date = new Date(yourTimestamp).toLocaleDateString('de-DE', {
    weekday: 'long',
    day: '2-digit',
    month: 'long',
    year: 'numeric'
})

结果:

Sonntag, 01. Januar 2023

另一种方式-从ISO 8601日期开始。

var时间戳=1293683278;var date=新日期(时间戳*1000);var iso=date.toISOString().match(/(\d{2}:\d{2})/)警报(iso[1]);

function getDateTime(unixTimeStamp) {

    var d = new Date(unixTimeStamp);
    var h = (d.getHours().toString().length == 1) ? ('0' + d.getHours()) : d.getHours();
    var m = (d.getMinutes().toString().length == 1) ? ('0' + d.getMinutes()) : d.getMinutes();
    var s = (d.getSeconds().toString().length == 1) ? ('0' + d.getSeconds()) : d.getSeconds();

    var time = h + '/' + m + '/' + s;

    return time;
}

var myTime = getDateTime(1435986900000);
console.log(myTime); // output 01/15/00