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

例如,HH/MM/SS格式。


当前回答

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

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

其他回答

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

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

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

不需要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时间戳:

const dateTimeString = moment.unix(1466760005).format("DD-MM-YYYY HH:mm:ss");

您可以使用以下函数将时间戳转换为HH:MM:SS格式:

var convertTime = function(timestamp, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    var date = timestamp ? new Date(timestamp * 1000) : new Date();
    return [
        pad(date.getHours()),
        pad(date.getMinutes()),
        pad(date.getSeconds())
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}

不传递分隔符,它使用:作为(默认)分隔符:

time = convertTime(1061351153); // --> OUTPUT = 05:45:53

如果要将/用作分隔符,只需将其作为第二个参数传递:

time = convertTime(920535115, '/'); // --> OUTPUT = 09/11/55

Demo

var convertTime=函数(时间戳,分隔符){var pad=函数(输入){return input<10?“0”+输入:输入;};var date=时间戳?new Date(时间戳*1000):new Date();返回[pad(date.getHours()),pad(date.getMinutes()),pad(date.getSeconds())].join(分隔符类型!==“undefined”?分隔符:“:”);}document.body.innerHTML=“<pre>”+JSON.stringify({920535115:转换时间(920535115,'/'),1061351153:转换时间(1061351153,“:”),1435651350:转换时间(1435651350,'-'),1487938926:转换时间(1487938926),1555135551:转换时间(1555135551,'.')},null,'\t')+'</pre>';

另请参见此Fiddle。