Java 7 and ThreeTen Backport
Michael’s answer is good. I’d just like to supply a few details. Since you mentioned in another question that you are using Java 7, I present code for Java 7.
First, the date-time classes that Michael is using, are not built into Java 7, but have been backported. So get the ThreeTen Backport that he mentions and import the date-time classes from the org.threeten.bp
package:
import org.threeten.bp.DateTimeUtils;
import org.threeten.bp.DayOfWeek;
import org.threeten.bp.LocalTime;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZonedDateTime;
Then add the following method to Michael’s WeekPeriod
class:
public boolean isInPeriod(ZonedDateTime dateTime) {
DayOfWeek dowToCheck = dateTime.getDayOfWeek();
LocalTime timeToCheck = dateTime.toLocalTime();
return dowToCheck.equals(day)
&& ! timeToCheck.isBefore(start)
&& timeToCheck.isBefore(end);
}
If you prefer the parameter to be a LocalDateTime
or an OffsetDateTime
, just change it, the code is the same. You can overload the method, of course, to accept all three types.
If you cannot avoid getting Calendar
objects, write one or two overloaded methods for them too. Convert your Calendar
to a ZonedDateTime
and call the above method. It‘s a bit more straightforward if your Calendar
is a GregorianCalendar
, which it probably is:
public boolean isInPeriod(GregorianCalendar cal) {
return isInPeriod(DateTimeUtils.toZonedDateTime(cal));
}
If it isn’t:
public boolean isInPeriod(Calendar cal) {
ZoneId zone = DateTimeUtils.toZoneId(cal.getTimeZone());
return isInPeriod(DateTimeUtils.toInstant(cal).atZone(zone));
}
All of the above works in Java 7 and in Java 6 too. I have tested on jdk1.7.0_79.
Java 8 and later
For anyone reading along and using Java 8 or later:
- Import the date-time classes from the
java.time
package instead (don’t use ThreeTen Backport).
- Instead of using
DateTimeUtils
convert using the methods that have been built into Calendar
and GregorianCalendar
from Java 8. For the GregorianCalendar
use cal.toZonedDateTime()
. For other Calendar
subclasses use cal.getTimeZone().toZoneId()
and then cal.toInstant()
.
Links