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

例如,HH/MM/SS格式。


当前回答

使用Moment.js,您可以获得如下时间和日期:

var dateTimeString = moment(1439198499).format("DD-MM-YYYY HH:mm:ss");

而且你只能使用这个:

var timeString = moment(1439198499).format("HH:mm:ss");

其他回答

不需要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 ) ) );

让unix_timestamp=1549312452//基于时间戳创建新的JavaScript Date对象//乘以1000,使参数以毫秒为单位,而不是以秒为单位。var date=新日期(unix_timestamp*1000);//时间戳的小时部分var hours=date.getHours();//时间戳的分钟部分var minutes=“0”+date.getMinutes();//时间戳的秒部分var seconds=“0”+date.getSeconds();//将以10:30:23格式显示时间var formattedTime=hours+‘:‘+minutes.substr(-2)+‘:’+seconds.substr(-3);console.log(格式化时间);

有关Date对象的更多信息,请参阅MDN或ECMAScript 5规范。

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

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

试试看:

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

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)