Borislav Hadzhiev
Tue Jan 18 2022·2 min read
Photo by Marcin Jozwiak
To remove the time from a date, use the getFullYear()
, getMonth()
and
getDate()
methods to get the year, month and date of the given date and pass
the results to the Date()
constructor. When values for the time components is
not provided, they default to 0
.
function removeTime(date = new Date()) { return new Date( date.getFullYear(), date.getMonth(), date.getDate() ); } // 👇️ Tue Jan 18 2022 00:00:00 console.log(removeTime(new Date())); // 👇️ Wed Jan 19 2022 00:00:00 console.log(removeTime(new Date(2022, 0, 19, 9, 30, 0)));
We created a reusable function, which removes the time from a Date
object.
The
Date()
constructor takes the year
, monthIndex
, day
, hours
, minutes
, seconds
and milliseconds
as parameters.
We used the following 3 date-related methods in the function:
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.
We didn't provide parameters for the hours
, minutes
, seconds
and
milliseconds
, so they all got set to 0
.
removeTime
function does not change the passed in Date
object, it returns a new Date
object.Alternatively, you could use the toDateString method.
Use the toDateString()
method to remove the time from a date, e.g.
new Date(date.toDateString())
. The method returns only the date portion of a
Date
object, so passing the result to the Date()
constructor would remove
the time from the date.
function removeTime(date = new Date()) { return new Date(date.toDateString()); } // 👇️ Tue Jan 18 2022 00:00:00 console.log(removeTime(new Date())); // 👇️ Wed Jan 19 2022 00:00:00 console.log(removeTime(new Date(2022, 0, 19, 9, 30, 0)));
The toDateString
method returns a string that contains only the date part of
the Date
object.
console.log(new Date().toDateString()); // 👉️ "Tue Jan 18 2022"
There is nothing that relates to the time in the string, so the hours, minutes,
seconds and milliseconds get set to 0
in the newly created Date
object.
Date()
constructor is easier for browsers to parse, than a non-ISO 8601 string.