【问题标题】:Get day resolution from unix time stamp从 unix 时间戳获取日期分辨率
【发布时间】:2013-11-03 19:43:49
【问题描述】:
我的理解是unix时间戳解析为毫秒
Math.round((new Date()).getTime()); // 1383507660267
所以如果我想要第二个解决方案,我会这样做
Math.round((new Date()).getTime() / 1000); // 1383507729
我会做些什么来获得当天的解决方案? (所以它只会每 24 小时更改一次)
【问题讨论】:
标签:
javascript
unix
unix-timestamp
【解决方案1】:
如果您必须应对夏令时时移,最好将时间戳标准化以反映某个特定时间,例如(任意)中午 12:00:
var daystamp = function() {
var d = new Date();
d.setHours(12);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
return d.getTime();
}();
这将为您提供生成它的当天中午的时间戳,因此,如果您在某个特定日历日期的任何时间获得它,它将始终为您提供相同的值。仅当日期不同时才会有所不同,无论一天中有多少小时。因此,当系统为时班添加或删除一个小时时,一切仍然有效。
【解决方案2】:
怎么样...
Math.round((new Date()).getTime() / (24 * 3600 * 1000));
这应该可以完成工作。甚至更简单:
(new Date()).getTime() / (24 * 3600 * 1000);
【解决方案3】:
你去吧,3种方法:
var roundedDate1 = function(timestamp) {
var t = new Date(timestamp);
t.setHours(0);
t.setMinutes(0);
t.setSeconds(0);
t.setMilliseconds(0);
return t;
};
var roundedDate2 = function(timestamp) {
var t = new Date(timestamp);
return new Date(t.getFullYear(), t.getMonth(), t.getDate(), 0, 0, 0, 0)
};
var roundedDate3 = function(timestamp) {
timestamp -= timestamp % (24 * 60 * 60 * 1000); // substract amount of time since midnight
timestamp += new Date().getTimezoneOffset() * 60 * 1000; // add the timezone offset
return new Date(timestamp);
};
var timestamp = 1417628530199;
console.log('1 ' + roundedDate1(timestamp));
console.log('2 ' + roundedDate2(timestamp));
console.log('3 ' + roundedDate3(timestamp));
// output
// 1 Wed Dec 03 2014 00:00:00 GMT+0100 (CET)
// 2 Wed Dec 03 2014 00:00:00 GMT+0100 (CET)
// 3 Tue Dec 02 2014 23:00:00 GMT+0100 (CET)
JSFiddle, JSBin
从这个来源略有修改:Round a timestamp to the nearest date