我将时间作为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;

其他回答

注意一些答案的零问题。例如,时间戳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

让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规范。

JavaScript以毫秒为单位工作,因此您必须首先将UNIX时间戳从秒转换为毫秒。

var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...

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()

最短的

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

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