How to check if the given time falls in mentioned time range
It’s not very clear. For this answer I am assuming that all of your times are to be understood in America/Chicago time zone. Please revert if this was not what you intended.
java.time
ZoneId zone = ZoneId.of("America/Chicago");
ZonedDateTime zdt = ZonedDateTime.now(zone).plusDays(2).plusMinutes(30);
LocalTime rangeStart = LocalTime.parse("10:11:13");
LocalTime rangeEnd = LocalTime.parse("18:49:00");
LocalTime time = zdt.toLocalTime();
if (!time.isBefore(rangeStart) && time.isBefore(rangeEnd)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
When I ran this code snippet just now (at 11:30 Chicago time), the output was:
Yes
I am using java.time, the modern Java date and time API, and recommend that you do the same. It’s so much nicer to work with than the old, outdated and poorly designed classes Date
, SimpleDateFormat
, Calendar
and TimeZone
.
A LocalTime
is a time of day from 00:00 (inclusive) to 24:00 (exclusive). By comparing LocalTime
objects we are ignoring the date and have no trouble with irrelevant dates in 1970 or some other time in history.
Edit:
Also is it possible to get the date and time of rangeStart and
rangeEnd in order to verify for which particular day and time we are
checking the conditions?
No, that would not make sense. Since a LocalTime
is a time of day without date, there is no way to get a date out of it. But you can print the ZonedDateTime
and verify its date part. And to assure yourself that the code is correct, write some unit tests.
Link: Oracle tutorial: Date Time explaining how to use java.time.
See if the current time falls within a specific range of time in the current day in Java
this is all you should need to do, this method is loosely coupled from the input and highly coherent.
boolean isNowBetweenDateTime(final Date s, final Date e)
{
final Date now = new Date();
return now.after(s) && now.before(e);
}
how you get the Date objects for start and end is irrelevant to comparing them. You are making things way more complicated than you need to with passing String
representations around.
Here is a better way to get the start and end dates, again loosely coupled and highly coherent.
private Date dateFromHourMinSec(final String hhmmss)
{
if (hhmmss.matches("^[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$"))
{
final String[] hms = hhmmss.split(":");
final GregorianCalendar gc = new GregorianCalendar();
gc.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hms[0]));
gc.set(Calendar.MINUTE, Integer.parseInt(hms[1]));
gc.set(Calendar.SECOND, Integer.parseInt(hms[2]));
gc.set(Calendar.MILLISECOND, 0);
return gc.getTime();
}
else
{
throw new IllegalArgumentException(hhmmss + " is not a valid time, expecting HH:MM:SS format");
}
}
Now you can make two well named method calls that will be pretty self documenting.
How to check if current time falls within a specific range considering also minutes
Something like this should work
var startTime = '6:30 PM';
var endTime = '8:30 AM';
var now = new Date();
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
if (startDate > endDate) { // check if start comes before end
var temp = startDate; // if so, assume it's across midnight
startDate = endDate; // and swap the dates
endDate = temp;
}
var open = now < endDate && now > startDate ? 'open' : 'closed'; // compare
console.log('Restaurant is ' + open);
function dateObj(d) { // date parser ...
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date;
}
.as-console-wrapper {top : 0!important}
Find if current time falls in a time range
For checking for a time of day use:
TimeSpan start = new TimeSpan(10, 0, 0); //10 o'clock
TimeSpan end = new TimeSpan(12, 0, 0); //12 o'clock
TimeSpan now = DateTime.Now.TimeOfDay;
if ((now > start) && (now < end))
{
//match found
}
For absolute times use:
DateTime start = new DateTime(2009, 12, 9, 10, 0, 0)); //10 o'clock
DateTime end = new DateTime(2009, 12, 10, 12, 0, 0)); //12 o'clock
DateTime now = DateTime.Now;
if ((now > start) && (now < end))
{
//match found
}
how to know if a date/time falls in some date/time range?
You can use this logic:
$start_date = '2012-07-10';
$end_date = '2012-10-06';
$date_from_user = '2009-08-28';
checkInRange($start_date, $end_date, $date_from_user);
function checkInRange($start_date, $end_date, $date_from_user)
{
// Convert to timestamp
$start_timestamp = strtotime($start_date);
$end_timestamp = strtotime($end_date);
$user_timestamp = strtotime($date_from_user);
// Check that user date is between start & end
return (($user_timestamp >= $start_timestamp) && ($user_timestamp <= $end_timestamp));
}
Hope this helps!
Related Topics
When Do Static Variables Get Initialized in C#
Change Desktop Wallpaper Using Code in .Net
Select Multiple Items from a Datagrid in an Mvvm Wpf Project
Do C# Timers Elapse on a Separate Thread
How to Generate an Image from Text on Fly at Runtime
A Method to Count Occurrences in a List
Check Whether Internet Connection Is Available with C#
Why Must I Provide Explicitly Generic Parameter Types While the Compiler Should Infer the Type
How to Check If Wpf Is Currently Executing in Design Mode or Not
What Is the Simplest Way to Get Indented Xml with Line Breaks from Xmldocument
Getting Path Relative to the Current Working Directory
Regex Match Multiple Times in String