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

后端 未结 9 2024
旧巷少年郎
旧巷少年郎 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:48

    Adding usefulness to @Dan's example, I had the need to find the next midday or midnight.

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

    This allowed me to set a frequency cap for an event, only allowing it to happen once in the morning and once in the afternoon for any visitor to my site. The date captured was used to set the expiration of the cookie.

提交回复
热议问题