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


当前回答

只是在这里添加这个,因为我在这个页面上寻找如何在moment.js中做到这一点,其他人也可能会这样做。

[理由:“时刻”这个词已经出现在本页的其他地方,所以搜索引擎直接指向这里,而moment.js的广泛应用足以保证在其他与日期相关的so问题中被提及的频率]

因此,在2.0.0及以上版本中:

date.startOf('day');

对于早期版本:

date.sod();

文档:

http://momentjs.com/docs/#/manipulating/start-of/

其他回答

对象配置的一行代码:

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

创建元素时:

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

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

// 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());

sehours方法可以采用可选的minutes, seconds和ms参数,例如:

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

这将把时间设置为当前时区的00:00:00.000,如果你想在UTC时间工作,你可以使用setUTCHours方法。

你可以用

new Date().setUTCHours(0,0,0,0)

如果您只需要该值一次。

使用dayjs库,你可以使用startOf('day')方法。

const dayjs = require('dayjs');

const todayAtMidnight= dayjs().startOf('day');

// Get as a native date object
console.log(todayAtMidnight.toDate());

要开始特定的一天,你可以使用以下命令:

const date = dayjs("2023-02-12").startOf('day');