So there's plenty of examples on how to calculate the time between two dates.
But in my case, I have a date X. Let's say it's today.
X has a time associate to it, e.g. 08:00 (Or what I get back from .getHours()
)
I need to know if the hours of X are between a start hour (say "07:00") and an end hour (say "12:00")
X will be always retrieved via getHours()
The start and end hour of the range have a fixed format (e.g. "07:00" and "12:00")
Performance is an issue, so whatever performs better is preferred (e.g. if it implies using moment
, that's fine, but if a custom function would perform better, we want that)
My first approach would be, as the formats are fixed, to transform the .getHours()
to a number, likewise for the range hours, and then calculate...I feel this approach my have trouble with some special cases I may not be aware of?
If you want to check part hours, consider converting the hours to minutes, something like the following. How will you deal with ranges that go over midnight? e.g. 23:30 to 01:30.
Are you dealing with military tine? (From 0:00 to 24:00)
getHours()
returns an Integer, and if you are only interested in hours and not minutes, you can use parseInt() to turn the start and end hours into integers as well. For example,parseInt('07:00', 10)
will return7
. So if you wanted to create a function to test if the current time is between two hours, it might look something like this:Then you would use it like this:
You could use moment-range
From docs: