I'm trying to check a current date and time is in between Friday 17:42 and Sunday 17:42 of the week with Java.
At the moment I'm doing this with really really bad code block. It was a hurry solution. Now I'm refactoring but I couldn't find any method in joda or etc.
Any ideas? Thanks
private final Calendar currentDate = Calendar.getInstance();
private final int day = currentDate.get(Calendar.DAY_OF_WEEK);
private final int hour = currentDate.get(Calendar.HOUR_OF_DAY);
private final int minute = currentDate.get(Calendar.MINUTE);
if (day != 1 && day != 6 && day != 7) {
if (combined != 0) {
return badge == 1;
} else {
return badge == product;
}
} else {
if (day == 6 && hour > 16) {
if (hour == 17 && minute < 43) {
if (combined != 0) {
return badge == 1;
} else {
return badge == product;
}
} else {
return badge == 0;
}
} else if (day == 6 && hour < 17) {
if (combined != 0) {
return badge == 1;
} else {
return badge == product;
}
} else if (day == 1 && hour > 16) {
if (hour == 17 && minute < 43) {
return badge == 0;
} else {
if (combined != 0) {
return badge == 1;
} else {
return badge == product;
}
}
} else {
return badge == 0;
}
}
I've used the solution like thiswith the help of @MadProgrammer and @Meno Hochschild
Method:
public static boolean isBetween(LocalDateTime check, LocalDateTime startTime, LocalDateTime endTime) {
return ((check.equals(startTime) || check.isAfter(startTime)) && (check.equals(endTime) || check.isBefore(endTime))); }
Usage:
static LocalDateTime now = LocalDateTime.now();
static LocalDateTime friday = now.with(DayOfWeek.FRIDAY).toLocalDate().atTime(17, 41);
static LocalDateTime sunday = friday.plusDays(2).plusMinutes(1);
if (!isBetween(now, friday, sunday)) { ... }
Thanks again for your efforts.
Date
andCalendar
have methods that can perform comparisons on other instances ofDate
/Calendar
,equals
,before
andafter
However, I'd encourage the use of Java 8's new Time API
Which will return
true
if the suppliedLocalDateTime
is within the specified range inclusively.Something like...
Which outputs
Joda-Time has an
Interval
class which makes it even eaiserwhich is demonstrated here
A different approach...
So I was thinking on way home, assuming all you have is the date/time you want to check, how you might determine if the day falls within your range
What this does is checks the
dayOfWeek
to see if it's within the desired range, if it is, it finds the previousFriday
and nextSunday
from the specified date and checks to see if it falls between them (see the previous example)lastFriday
andnextSunday
simply adds/subtracts aday
from the specified date/time until to reaches the desireddayOfWeek
, it then seeds the required time constraints