Borislav Hadzhiev
Fri Jan 14 2022·2 min read
Photo by Sylwia Bartyzel
Use the setUTCHours()
method to get the start and end of the day, e.g.
startOfDay.setUTCHours(0, 0, 0, 0)
. The method takes the hours, minutes,
seconds and milliseconds as parameters and sets them for the specified date
according to universal time.
// ✅ In UTC (international time standard) // - keeps code consistent across time zones const startOfDay = new Date(); startOfDay.setUTCHours(0, 0, 0, 0); console.log(startOfDay); const endOfDay = new Date(); endOfDay.setUTCHours(23, 59, 59, 999); console.log(endOfDay); // ✅ In Local Time (time zone the visitor's computer is in) // - will differ for users with different GEOs const start = new Date(); start.setHours(0, 0, 0, 0); console.log(start); const end = new Date(); end.setHours(23, 59, 59, 999); console.log(end);
We used the Date() constructor to get a date object that represents the current date and time.
In the first example, we used the setUTCHours method.
The method takes 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.setUTCHours
method sets the provided values on the specified date according to universal time (UTC).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.
In the second example, we used the user's local time to get the start and end of the day. Local time refers to the time zone the visitor's computer is in.
// ✅ In Local Time (time zone the visitor's computer is in) // - will differ for users with different GEOs const start = new Date(); start.setHours(0, 0, 0, 0); console.log(start); const end = new Date(); end.setHours(23, 59, 59, 999); console.log(end);
We used the
setHours
method instead of setUTCHours
.
setHours
sets the provided values on the date according to local time (the visitor's local time).Depending on where the user visits your site from, this would yield different results.
The setUTCHours
method does the same, but according to universal time.
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.