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

例如,HH/MM/SS格式。


当前回答

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

其他回答

注意一些答案的零问题。例如,时间戳1439329773将错误地转换为2015年8月12日0:49。

我建议使用以下方法来解决这个问题:

var timestamp = 1439329773; // replace your timestamp
var date = new Date(timestamp * 1000);
var formattedDate = ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
console.log(formattedDate);

现在的结果是:

12/08/2015 00:49

不需要40 KB库的现代解决方案:

Intl.DateTimeFormat是格式化日期/时间的非文化帝国主义方式。

// Setup once
var options = {
    //weekday: 'long',
    //month: 'short',
    //year: 'numeric',
    //day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric'
},
intlDate = new Intl.DateTimeFormat( undefined, options );

// Reusable formatter
var timeStamp = 1412743273;
console.log( intlDate.format( new Date( 1000 * timeStamp ) ) );

参见日期/年代转换器。

您需要ParseInt,否则它将无法工作:


if (!window.a)
    window.a = new Date();

var mEpoch = parseInt(UNIX_timestamp);

if (mEpoch < 10000000000)
    mEpoch *= 1000;

------
a.setTime(mEpoch);
var year = a.getFullYear();
...
return time;

下面的代码还提供了3位毫秒,非常适合控制台日志前缀:

const timeStrGet=日期=>{const milliSecsStr=date.getMilliseconds().toString().padStart(3,“0”);返回`${date.toLocaleTimeString('it-US')}.${milliSecsStr}`;};setInterval(()=>console.log(timeStrGet(new Date())),299);

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)