What is the best way to initialize a JavaScript Date to midnight?

后端 未结 9 1956
旧巷少年郎
旧巷少年郎 2020-11-29 15:38

What is the simplest way to obtain an instance of new Date() but set the time at midnight?

相关标签:
9条回答
  • 2020-11-29 16:01

    A one-liner for object configs:

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

    When creating an element:

    dateFieldConfig = {
          name: "mydate",
          value: new Date(new Date().setHours(0, 0, 0, 0)),
    }
    
    0 讨论(0)
  • 2020-11-29 16:05

    The setHours method can take optional minutes, seconds and ms arguments, for example:

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

    That will set the time to 00:00:00.000 of your current timezone, if you want to work in UTC time, you can use the setUTCHours method.

    0 讨论(0)
  • 2020-11-29 16:05

    I have made a couple prototypes to handle this for me.

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

    if you dont want the saftey check, then you can just use

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

    Example usage:

    var date = new Date($.now()); // $.now() requires jQuery
    console.log('startOfDay: ' + date.startOfDay());
    console.log('endOfDay: ' + date.endOfDay());
    
    0 讨论(0)
提交回复
热议问题