繁体   English   中英

从Unix时间戳获取日分辨率

[英]Get day resolution from unix time stamp

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

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

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

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

我该怎么做才能获得日间解决方案? (因此,它只会每24小时更改一次)

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

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

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

关于什么 ...

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

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

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

您可以通过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)

JSFiddleJSBin

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM