Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 20, 2021 06:15 am GMT

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()

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)

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)

And guess what would the end date be? Same.

Sun Jun 20 2021 00:00:00 GMT+0500 (Pakistan Standard Time)

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))

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

new Date(new Date().setHours(00,00,00,0))

and end date should be

new Date(new Date().setHours(23,59,59,0))

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


Original Link: https://dev.to/mursalfk/using-sethours-to-get-customized-time-with-date-1ooo

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To