0

我的理解是unix时间戳解析为毫秒

Math.round((new Date()).getTime()); // 1383507660267

所以如果我想要第二个解决方案,我会做

Math.round((new Date()).getTime() / 1000); // 1383507729

我该怎么做才能获得当天的解决方案?(所以它只会每 24 小时更改一次)

4

3 回答 3

3

如果您必须应对夏令时时间变化,最好将时间戳标准化以反映某个特定时间,例如(任意)中午 12:00:

var daystamp = function() {
  var d = new Date();
  d.setHours(12);
  d.setMinutes(0);
  d.setSeconds(0);
  d.setMilliseconds(0);
  return d.getTime();
}();

这将在您生成它的当天中午为您提供时间戳,因此如果您在某个特定日历日期的任何时间获得它,它将始终为您提供相同的值。仅当日期不同时才会有所不同,无论一天中有多少小时。因此,当系统为时班添加或删除一个小时时,一切仍然有效。

于 2013-11-03T19:52:22.190 回答
2

关于什么 ...

Math.round((new Date()).getTime() / (24 * 3600 * 1000));

那应该做的工作。甚至更简单:

(new Date()).getTime() / (24 * 3600 * 1000);
于 2013-11-03T19:46:08.827 回答
0

你去吧,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

从此来源稍作修改:将时间戳四舍五入到最近的日期

于 2015-09-10T17:01:38.497 回答