Set only the Date ignoring Time using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 19, 2022

banner

Photo from Unsplash

Set only the Date ignoring Time using JavaScript #

Use the setHours() method to set only the date, ignoring time, e.g. date.setHours(0, 0, 0, 0). The setHours methods takes the hours, minute, seconds and milliseconds as parameters and changes the Date object according to the provided values.

index.js
const date = new Date(); // ✅ Reset a Date's time to midnight date.setHours(0, 0, 0, 0); // 👇️ Wed Jan 19 2022 00:00:00 console.log(date);

The setHours method takes the hours, minutes, seconds and milliseconds as parameters and changes the value for the given Date object.

If you have a Date object and want to set only the Date ignoring the time, you can use the toDateString() method and pass the date string to the Date() constructor.

index.js
const dateAndTime = new Date(2022, 3, 24, 9, 30); const date = new Date(dateAndTime.toDateString()); // 👇️ Sun Apr 24 2022 00:00:00 console.log(date);

The toDateString method returns the date portion of a Date object.

index.js
const dateAndTime = new Date(2022, 3, 24, 9, 30); // 👇️ Sun Apr 24 2022 console.log(dateAndTime.toDateString());
The string returned from the toDateString method does not contain any information about the time, so the date's time gets set to 00:00:00.

You can also use the getFullYear, getMonth and getDate methods to set only the date, without setting the time.

index.js
const dateAndTime = new Date(2022, 3, 24, 9, 30); const date = new Date( dateAndTime.getFullYear(), dateAndTime.getMonth(), dateAndTime.getDate(), ); // 👇️ Sun Apr 24 2022 00:00:00 console.log(date);

The Date() constructor takes the year, month (January = 0, February = 1), day of the month, hours, minutes, seconds and milliseconds as parameters.

We used the following 3 Date related methods to get the year, month and day of the month from the Date object:

  • 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.

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.