我的理解是,Unix的时间戳解析为毫秒找一天分辨率
Math.round((new Date()).getTime()); // 1383507660267
所以如果我想第二项决议,我会做
Math.round((new Date()).getTime()/1000); // 1383507729
我会怎么做得到日分辨率? (所以它只会改变每24小时)
我的理解是,Unix的时间戳解析为毫秒找一天分辨率
Math.round((new Date()).getTime()); // 1383507660267
所以如果我想第二项决议,我会做
Math.round((new Date()).getTime()/1000); // 1383507729
我会怎么做得到日分辨率? (所以它只会改变每24小时)
怎样......
Math.round((new Date()).getTime()/(24 * 3600 * 1000));
这应该做的工作。甚至simplier:
(new Date()).getTime()/(24 * 3600 * 1000);
如果您在使用夏令时的变化抗衡,它可能会更好正常化的时间戳,以反映某些特定时间,如(任意)中午12:00:
var daystamp = function() {
var d = new Date();
d.setHours(12);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
return d.getTime();
}();
这会给你在生成它的那天中午的时间戳,所以如果你在某个特定的日历日期随时得到它,它总会给你相同的价值。只有在日期不同的情况下,不管一天中有多少个小时,情况都会有所不同。因此,当系统为时间转移添加或删除一小时时,事情仍然有效。
你去那里,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)
从这个来源稍加修改:Round a timestamp to the nearest date