gpt4 book ai didi

JavaScript unixtime 问题

转载 作者:行者123 更新时间:2023-11-28 16:32:34 26 4
gpt4 key购买 nike

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

它看起来像这样:console.log(时间);结果: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);

最佳答案

It looks like this: console.log (time); Result: 1300709088000

这看起来不像 Unix 时间戳(自 The Epoch 以来的秒数),它看起来像自 The Epoch 以来的毫秒。因此,对于 JavaScript,您不会乘以 1000 来将秒转换为毫秒,它已经以毫秒为单位了(或者您正在处理距现在 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 .

关于JavaScript unixtime 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5377486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com