将UNIX时间戳转换为日期时间(javascript)

时间:2014-06-11 19:20:50

标签: javascript

时间戳:

1395660658

代码:

//timestamp conversion
exports.getCurrentTimeFromStamp = function(timestamp) {
    var d = new Date(timestamp);
    timeStampCon = d.getDate() + '/' + (d.getMonth()) + '/' + d.getFullYear() + " " + d.getHours() + ':' + d.getMinutes();

    return timeStampCon;
};

这会根据时间格式正确转换时间戳,但日期始终为:

17/0/1970

为什么 - 干杯?

4 个答案:

答案 0 :(得分:21)

自从纪元(即01/01/1970)以来,你需要乘以1000,以千分之一秒为单位,而不是秒:

var d = new Date(timestamp*1000);

Reference

答案 1 :(得分:2)

因为你的时间是几秒钟。自从纪元以来,Javascript要求它在几毫秒内。乘以1000,它应该是你想要的。

//time in seconds
var timeInSeconds = ~(new Date).getTime();
//invalid time
console.log(new Date(timeInSeconds));
//valid time
console.log(new Date(timeInSeconds*1000));

答案 2 :(得分:0)

NUMBER       DATE
1      20 2017-01-01
3      40 2017-01-03
5      50 2017-01-05
7      60 2017-01-07
8      20 2017-01-08
10     40 2017-01-10
12     50 2017-01-12
14     60 2017-01-14
   NUMBER       DATE
1      20 2017-01-01
3      40 2017-01-03
5      50 2017-01-05
7      60 2017-01-07
8      20 2017-01-08
10     40 2017-01-10
12     50 2017-01-12
14     60 2017-01-14

您可以通过调用function convertTimestamp(timestamp) { var d = new Date(timestamp * 1000), // Convert the passed timestamp to milliseconds yyyy = d.getFullYear(), mm = ('0' + (d.getMonth() + 1)).slice(-2), // Months are zero based. Add leading 0. dd = ('0' + d.getDate()).slice(-2), // Add leading 0. hh = d.getHours(), h = hh, min = ('0' + d.getMinutes()).slice(-2), // Add leading 0. ampm = 'AM', time; if (hh > 12) { h = hh - 12; ampm = 'PM'; } else if (hh === 12) { h = 12; ampm = 'PM'; } else if (hh == 0) { h = 12; } // ie: 2014-03-24, 3:00 PM time = yyyy + '-' + mm + '-' + dd + ', ' + h + ':' + min + ' ' + ampm; return time; }

来获取值

答案 3 :(得分:0)

const timeStamp = 1611214867768;

const dateVal = new Date(timeStamp).toLocaleDateString('en-US');
console.log(dateVal)