获取new Date()实例但将时间设置为午夜的最简单方法是什么?


当前回答

我已经做了几个原型来处理这个问题。

// This is a safety check to make sure the prototype is not already defined.
Function.prototype.method = function (name, func) {
    if (!this.prototype[name]) {
        this.prototype[name] = func;
        return this;
    }
};

Date.method('endOfDay', function () {
    var date = new Date(this);
    date.setHours(23, 59, 59, 999);
    return date;
});

Date.method('startOfDay', function () {
    var date = new Date(this);
    date.setHours(0, 0, 0, 0);
    return date;
});

如果你不想要安全检查,那么你可以直接使用

Date.prototype.startOfDay = function(){
  /*Method body here*/
};

使用示例:

var date = new Date($.now()); // $.now() requires jQuery
console.log('startOfDay: ' + date.startOfDay());
console.log('endOfDay: ' + date.endOfDay());

其他回答

只是想澄清一下,接受答案的片段给出了过去最近的午夜:

var d = new Date();
d.setHours(0,0,0,0); // last midnight

如果你想在将来得到最近的午夜,使用下面的代码:

var d = new Date();
d.setHours(24,0,0,0); // next midnight

我已经做了几个原型来处理这个问题。

// This is a safety check to make sure the prototype is not already defined.
Function.prototype.method = function (name, func) {
    if (!this.prototype[name]) {
        this.prototype[name] = func;
        return this;
    }
};

Date.method('endOfDay', function () {
    var date = new Date(this);
    date.setHours(23, 59, 59, 999);
    return date;
});

Date.method('startOfDay', function () {
    var date = new Date(this);
    date.setHours(0, 0, 0, 0);
    return date;
});

如果你不想要安全检查,那么你可以直接使用

Date.prototype.startOfDay = function(){
  /*Method body here*/
};

使用示例:

var date = new Date($.now()); // $.now() requires jQuery
console.log('startOfDay: ' + date.startOfDay());
console.log('endOfDay: ' + date.endOfDay());

对象配置的一行代码:

new Date(new Date().setHours(0,0,0,0));

创建元素时:

dateFieldConfig = {
      name: "mydate",
      value: new Date(new Date().setHours(0, 0, 0, 0)),
}

如果用日期计算,夏季时间通常会比午夜(CEST)多1小时或少1小时。当日期返回时,这将导致1天的差异。所以日期必须四舍五入到最近的午夜。所以代码将是(感谢jamisOn):

    var d = new Date();
    if(d.getHours() < 12) {
    d.setHours(0,0,0,0); // previous midnight day
    } else {
    d.setHours(24,0,0,0); // next midnight day
    }

如果您已经在项目中有d3.js作为依赖项,或者不介意引入它,d3-time (d3.js库在v4.0.0中是模块化的)有interval。

在将日期设置为“默认”值时,它们可能很有用,例如午夜、0.00秒、每月的第一天等。

var d = new Date(); // Wed Aug 02 2017 15:01:07 GMT+0200 (CEST)
d3.timeHour(d) // Wed Aug 02 2017 00:00:00 GMT+0200 (CEST)
d3.timeMonth(d) // Tue Aug 01 2017 00:00:00 GMT+0200 (CEST)