Borislav Hadzhiev
Last updated: Jan 14, 2022
Check out my new book
Use the 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 Date
instance.
// 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
Date()
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 0
and 23
that represents the hour.minutesValue
(optional) - an integer between 0
and 59
that represents
the minutes.secondsValue
(optional) - an integer between 0
and 59
that represents
the seconds.msValue
(optional) - a number between 0
and 999
that represents the
milliseconds.0
for all 4 values to set the Date
object 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.
23
is passed for the hours, the Date
object 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 setUTCHours()
instead of setHours()
.
// ✅ (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
setUTCHours
method instead of setHours
.
setHours
sets the provided values on the date, according to local time (the visitor's local time), whereas the setUTCHours
method 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.