DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Using .setHours() to get customized time with date πŸ“…
Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on • Updated on

Using .setHours() to get customized time with date πŸ“…

Hello Folks πŸ‘‹
In this article, we will be discussing how we can get customized time when you select a date in React.
Usually it happens, when developers are asked to use date fields to select a date range, JavaScript does so with utmost sleekness by using

new Date()
Enter fullscreen mode Exit fullscreen mode

But one of the biggest drawback of using this approach is, the resulting date would also contain a time tag, since in JavaScript date and time are always fetched together from the system and it is on us what aspect we want to use, either the date, or the time. The results would be

Sun Jun 20 2021 10:51:18 GMT+0500 (Pakistan Standard Time)
Enter fullscreen mode Exit fullscreen mode

Now for suppose, as in my case, we have to fetch some data within a given time range, and the user wants to retrieve records from a single day. With simple understanding, the user would select the start and end date to be the same. Now what does JavaScript do, the start date, for suppose, today, 20th June 2021, would come as:

Sun Jun 20 2021 00:00:00 GMT+0500 (Pakistan Standard Time)
Enter fullscreen mode Exit fullscreen mode

And guess what would the end date be? Same.

Sun Jun 20 2021 00:00:00 GMT+0500 (Pakistan Standard Time)
Enter fullscreen mode Exit fullscreen mode

It means, that the user's query would be to check records from 12 in the Midnight of the same day to 12 on the midnight of the same day. Giving us Zero (0) records in the output.
To sort out this problem, we can use .setHours() function of JavaScript.

Benefits

  • Set your desired time for the day
  • Escape from selecting system specified time
  • There can be more benefits

Solution

Now it will be useless to use this function when defining the start date. Right? Wrong! For a safety measure, you must use it on start and end date, both. But with different parameters.

Syntax

.setHours is used with Date over Date to convolute the results in a better way.

new Date(new Date().setHours(HH,MM,SS,mm))
Enter fullscreen mode Exit fullscreen mode

In order to use it on start date, it should be

new Date(new Date().setHours(00,00,00,0))
Enter fullscreen mode Exit fullscreen mode

and end date should be

new Date(new Date().setHours(23,59,59,0))
Enter fullscreen mode Exit fullscreen mode

Using this technique, you can easily allow and enable the user to select records from a whole day. πŸ˜‰

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

β­οΈπŸŽ€ JavaScript Visualized: Promises & Async/Await

async await