JavaScript unixtime问题

时间:2011-03-21 12:20:09

标签: javascript unix-timestamp

我从Unix格式的数据库中获取时间。

它看起来像这样:console.log(time); 结果:1300709088000

现在我想重新格式化并只挑选时间,我发现了这个:Convert a Unix timestamp to time in JavaScript

这不能按我的意愿行事。我得到的时间是:

1300709088000
9:0:0

1300709252000
6:33:20

1300709316000
0:20:0

1300709358000
12:0:0

1300709530000
11:46:40

当我知道时代完全不同时,这是非常错误的时期。我该如何解决?

    console.log(time);

var date = new Date(time*1000);
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = date.getMinutes();
// seconds part from the timestamp
var seconds = date.getSeconds();

// will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes + ':' + seconds;
console.log(formattedTime);

3 个答案:

答案 0 :(得分:3)

  

它看起来像这样:console.log(time);结果:1300709088000

这看起来不像Unix时间戳(自The Epoch以来的秒数),自Epoch以来它看起来像毫秒。所以你不会乘以1000来将JavaScript从秒转换为毫秒,它已经是毫秒(或者你要处理超过41,000年后的日期;这是公平的)。

测试:

var times = [
    1300709088000,
    1300709252000,
    1300709316000,
    1300709358000,
    1300709530000
  ];
var index;

for (index = 0; index < times.length; ++index) {
    display(times[index] + " => " + new Date(times[index]));
}

Live copy


更新:或获取各个部分:

var times = [
    1300709088000,
    1300709252000,
    1300709316000,
    1300709358000,
    1300709530000
  ];
var index, dt;

for (index = 0; index < times.length; ++index) {
    dt = new Date(times[index]);
    display(times[index] +
            " => " +
            dt +
            " (" + formatISOLikeDate(dt) + ")");
}

// Not all implementations have ISO-8601 stuff yet, do it manually
function formatISOLikeDate(dt) {
    var day    = String(dt.getDate()),
        month  = String(dt.getMonth() + 1), // Starts at 0
        year   = String(dt.getFullYear()),
        hour   = String(dt.getHours()),
        minute = String(dt.getMinutes()),
        second = String(dt.getSeconds());

    return zeroPad(year, 4) + "-" +
           zeroPad(month, 2) + "-" +
           zeroPad(day, 2) + " " +
           zeroPad(hour, 2) + ":" +
           zeroPad(minute, 2) + ":" +
           zeroPad(second, 2);
}
function zeroPad(str, width) {
    while (str.length < width) {
        str = "0" + str;
    }
    return str;
}

Live copy ...但是如果你要做任何关于日期的事情,我会看DateJS

答案 1 :(得分:1)

您的时间戳在Unix格式中,它们已经采用Javascript 毫秒分辨率格式。

因此,在创建Date对象时,不应该乘以1000。

答案 2 :(得分:0)

我试过这样的事情:

console.log(时间);

 where date = new Date (time);
 / / hours party from the timestamp
 was hours = date.getHours ();
 / / party minutes from the timestamp
 Every minute = date.getMinutes ();
 / / Seconds Party From The timestamp
 where seconds = date.getSeconds ();

 / / Will display time up 10:30:23 format
 was formattedTime = hours + ':' + minutes + ':' + seconds;
 console.log (formattedTime);

结果如下: 1300709088000 NaN:NaN:NaN