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

IT技术 javascript
2021-02-04 18:03:54

时间戳:

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个回答

您必须乘以 1000,因为 JavaScript 从纪元(即 01/01/1970)开始以毫秒为单位计数,而不是秒:

var d = new Date(timestamp*1000);

参考

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;
}

您可以通过调用获取值 convertTimestamp('1395660658')

因为你的时间是以秒为单位的。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));
const timeStamp = 1611214867768;

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