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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24170933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:17:33  来源:igfitidea点击:

Convert UNIX timestamp to date time (javascript)

javascript

提问by bobo2000

Timestamp:

时间戳:

1395660658

Code:

代码:

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

    return timeStampCon;
};

This converts the time stamp properly in terms of time format, but the date is always:

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

17/0/1970

Why - cheers?

为什么 - 干杯?

回答by Denys Séguret

You have to multiply by 1000 as JavaScript counts in milliseconds since epoch (which is 01/01/1970), not seconds :

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

var d = new Date(timestamp*1000);

Reference

参考

回答by wbennett

Because your time is in seconds. Javascript requires it to be in milliseconds since epoch. Multiply it by 1000 and it should be what you want.

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

回答by kamal shooryabi

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

You can get the value by calling like convertTimestamp('1395660658')

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