Borislav Hadzhiev
Last updated: Jul 26, 2022
Photo from Unsplash
Use the setHours()
method to set a date's hours, minutes and seconds to 0
,
e.g. date.setHours(0, 0, 0, 0)
. The setHours
method takes the hours,
minutes, seconds and milliseconds as parameters and sets the values on the
date.
const date = new Date(); date.setHours(0, 0, 0, 0); console.log(date); // 👉️ Sat Jan 22 2022 00:00:00
We used the
Date.setHours
method to set the hours, minutes and seconds of a date to 0
.
The 4 parameters we passed to the methods are:
hours
- an integer between 0
and 23
that represents the hours.minutes
(optional) - an integer between 0
and 59
that represents the
minutes.seconds
(optional) - an integer between 0
and 59
that represents the
seconds.milliseconds
(optional) - a number between 0
and 999
that represents
the milliseconds.setHours()
method changes the values of the Date
object in place.If you want to create a new Date
object with the same date, where the values
for the hours, minutes and seconds are set to 0
, create a copy of the Date
before calling the setHours
method.
const date = new Date(); const dateCopy = new Date(date.getTime()); dateCopy.setHours(0, 0, 0, 0); console.log(dateCopy); // Sat Jan 22 2022 00:00:00 // 👇️ didn't change original console.log(date); // 👉️ Sat Jan 22 2022 16:34:40
We used the getTime
method to get the number of milliseconds elapsed between
the 1st of January, 1970 00:00:00 and the given date.
Date()
constructor to create a copy of the Date
object, so we don't mutate it in place when calling the setHours
method.Copying the date is quite useful when you have to use the original Date
object
in other places in your code.
An alternative approach is to use the getFullYear
, getMonth
and getDate
methods to create a new Date
object where the hours, minutes and seconds are
set to 0
.
const date = new Date(); const withoutTime = new Date( date.getFullYear(), date.getMonth(), date.getDate(), ); console.log(withoutTime); // 👉️ Sat Jan 22 2022 00:00:00
The 3 parameters we passed to the Date() constructor are:
year
- a 4-digit integer value representing the year of the date.monthIndex
- an integer value from 0 (January) to 11 (December) that
represents the month.day
- an integer value representing the day of the month.We used the following 3 date-related methods:
Date.getFullYear method - returns a four-digit number representing the year that corresponds to a date.
Date.getMonth -
returns an integer between 0
(January) and 11
(December) and represents
the month for a given date. Yes, unfortunately the getMonth
method is off
by 1
.
Date.getDate -
returns an integer between 1
and 31
representing the day of the month for
a specific date.
hours
, minutes
, seconds
and milliseconds
, so they all got set to 0
.