Node.JS - 将UNIX时间戳转换为时间 - 时区移位

时间:2012-10-21 15:27:10

标签: javascript node.js date time timestamp

我有一个将时间戳转换为时间的函数:

function convertUnixTimeToTime(UNIX_timestamp) {
    var a = new Date(UNIX_timestamp);
    var fin_hour = String(a.getHours())
    if (fin_hour.length == 1) {
        fin_hour = '0' + fin_hour;
    }
    var fin_minutes = String(a.getMinutes())
    if (fin_minutes.length == 1) {
        fin_minutes = '0' + fin_minutes;
    }
    var time = fin_hour + ':' + fin_minutes;
    return time;
}

我正在本地测试我的应用程序,我的计算机的时移是+4。 当我尝试从节点应用程序获取当前时间时:

console.log('Current time is: ' + convertUnixTimeToTime(new Date().getTime()));

我的当前本地时间。正如我所想的,Date()。getTime()应该以毫秒为单位返回绝对UNIX时间。我的函数convertUnixTimeToTime()没有指定任何时移,这就是为什么我应该在没有任何转换的情况下获得清晰的时间。我为什么要换+4次?感谢。

2 个答案:

答案 0 :(得分:2)

getHoursgetMinutes函数始终返回本地时间。 new Date(new Date().getTime())比其他任何内容都更令人困惑 - 它与new Date()相同 - 它不会改变任何关于时区的内容。

要获得所需内容,请使用getUTCHoursgetUTCMinutes

答案 1 :(得分:1)

因为定义Date.getHours()Date.getMinutes()会返回本地时间吗?