Remove the Time from a Date using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Remove the Time from a Date using JavaScript #

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 are not provided, they default to 0.

index.js
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 that 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.

Note that the removeTime function doesn't 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.

index.js
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.

index.js
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.

Which approach you pick is a matter of personal preference. I'd go with the first approach because passing multiple parameters to the Date() constructor is easier for browsers to parse, than a non-ISO 8601 string.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.