Last updated: Jan 14, 2022
Check out my new book
setHours() method to initialize a date to midnight, e.g.
d.setHours(0, 0, 0, 0). The
setHours method takes the hours, minutes,
seconds and milliseconds as parameters and sets the value on the
// Time of writing article = 14th January, 2022 // ✅ Set date to Nearest Midnight in the Past const d1 = new Date(); d1.setHours(0, 0, 0, 0); console.log(d1); // Fri Jan 14 2022 00:00:00 // ✅ Set date to Nearest Midnight in the future const d2 = new Date(); d2.setHours(24, 0, 0, 0); console.log(d2); // Sat Jan 15 2022 00:00:00
We used the
constructor to create a
Date object that represents the current date and time.
The setHours method takes the following 4 parameters:
hoursValue- an integer between
23that represents the hour.
minutesValue(optional) - an integer between
59that represents the minutes.
secondsValue(optional) - an integer between
59that represents the seconds.
msValue(optional) - a number between
999that represents the milliseconds.
0for all 4 values to set the
Dateobject to the nearest midnight in the past.
In the second example, we passed
24 as the value for the hours to set the date
to the nearest midnight in the future.
23is passed for the hours, the
Dateobject automatically rolls over to the next day.
Note that the
setHours() method sets the time according to the visitor's
local time (time zone the visitor's computer is in).
If you want to initialize a date to midnight in UTC, use the
// ✅ (UTC) Set date to Nearest Midnight in the Past const d1 = new Date(); d1.setUTCHours(0, 0, 0, 0); console.log(d1); // ✅ (UTC) Set date to Nearest Midnight in the future const d2 = new Date(); d2.setUTCHours(24, 0, 0, 0); console.log(d2);
We used the
method instead of
setHourssets the provided values on the date, according to local time (the visitor's local time), whereas the
setUTCHoursmethod does that according to universal time.
UTC (Coordinated Universal Time) and GMT share the same current time.
The difference between the two is that UTC is a time standard and GMT is a time zone.
UTC is an international time standard, which is used for consistency between time zones.
For consistency, you should mostly use local time when you have to render a date and time to the user, but store the actual values in UTC.