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

例如,HH/MM/SS格式。


当前回答

参见日期/年代转换器。

您需要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;

其他回答

function timeConverter(UNIX_timestamp){
 var a = new Date(UNIX_timestamp*1000);
     var hour = a.getUTCHours();
     var min = a.getUTCMinutes();
     var sec = a.getUTCSeconds();
     var time = hour+':'+min+':'+sec ;
     return time;
 }

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

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

而且你只能使用这个:

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

函数getDateTimeFromTimestamp(unixTimeStamp){let date=新日期(unixTimeStamp);return('0'+date.getDate()).slice(-2)+'/'+('0'+(date.getMonth()+1)).sslice(-2)+'/'+date.getFullYear()+''+('0'+date.getHours()).slice(-2')+':'+('0'+date.get-Minutes())slice(-2';}const myTime=getDateTimeFromTimestamp(1435986900000);console.log(myTime);//输出01/05/2000 11:00

Use:

var s = new Date(1504095567183).toLocaleDateString("en-US")
console.log(s)
// expected output "8/30/2017"  

时间:

var s = new Date(1504095567183).toLocaleTimeString("en-US")
console.log(s)
// expected output "3:19:27 PM"

请参见Date.protype.toLocaleDateString()

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