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

后端 未结 9 2023
旧巷少年郎
旧巷少年郎 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 15:56

    If calculating with dates summertime will cause often 1 uur more or one hour less than midnight (CEST). This causes 1 day difference when dates return. So the dates have to round to the nearest midnight. So the code will be (ths to 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
        }
    

提交回复
热议问题