JavaScript unixtime 问题
我从数据库中获取 Unix 格式的时间。
它看起来像这样:console.log(时间); 结果:1300709088000
现在我想重新格式化它并只选择时间,我发现了这个: 在 JavaScript 中将 Unix 时间戳转换为时间
这并没有按照我想要的方式工作。我得到的时间是这样的:
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);
I get the time from the database in Unix format.
It looks like this: console.log (time);
Result: 1300709088000
Now I want to reformat it and pick out only the time, I found this: Convert a Unix timestamp to time in JavaScript
That did not work as I want. The time I get is this:
1300709088000
9:0:0
1300709252000
6:33:20
1300709316000
0:20:0
1300709358000
12:0:0
1300709530000
11:46:40
It is very wrong times when I know that times are quite different. How can I fix it?
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这看起来不像 Unix 时间戳(自大纪元以来的秒数),它看起来像自大纪元以来的毫秒。因此,对于 JavaScript,您不会乘以 1000 来从秒转换为毫秒,它已经以毫秒为单位了(或者您正在处理距现在 41,000 多年的日期;这很公平)。
测试:
Live copy
更新:或获取各个部分:
Live copy ...但是如果你要对日期做很多事情,我会看看DateJS。
That doesn't look like a Unix timestamp (seconds since The Epoch), it looks like milliseconds since The Epoch. So you wouldn't multiply by 1000 to convert from seconds to milliseconds for JavaScript, it's already in milliseconds (or you're dealing with dates more than 41,000 years from now; which is fair enough).
Test:
Live copy
Update: Or getting the individual parts:
Live copy ...but if you're going to be doing much of anything with dates, I'd look at DateJS.
您的时间戳不是采用Unix格式,它们已经采用Javascript毫秒分辨率格式。
因此,当您创建
Date
对象时,不应乘以 1000。Your time stamps are not in Unix format, they're already in the Javascript millisecond resolution format.
Hence you shouldn't be multiplying by 1000 when you create your
Date
object.我尝试做这样的事情:
console.log (time);
结果是这样的:
1300709088000
南: 南: 南
I've tried to do something like this:
console.log (time);
The result is this:
1300709088000
NaN: NaN: NaN