Hurricane season is a time period between June 1st through Novemeber 30th. This example implements the TemporalQuery interface with the queryFrom(TemporalAccessor) method and allows for a way to extract information from a temporal object. The queryFrom method compares the passed-in date against with a MonthDay object, a class that represents the combination of a month and day. It then returns true if it is between June 1st and Novemeber 30th.
Setup
public class HurricaneSeasonQuery implements TemporalQuery<Boolean> {
/*
* (non-Javadoc)
* @see java.time.temporal.TemporalQuery#queryFrom(java.time.temporal.TemporalAccessor)
*/
@Override
public Boolean queryFrom(TemporalAccessor temporal) {
LocalDate date = LocalDate.from(temporal);
MonthDay juneFirst = MonthDay.of(Month.JUNE.getValue(), 1);
MonthDay novemberThirty = MonthDay.of(Month.NOVEMBER.getValue(), 30);
if (date.isAfter(juneFirst.atYear(date.getYear()))
&& date.isBefore(novemberThirty.atYear(date.getYear()))) {
return true;
} else {
return false;
}
}
}
Is before hurricane season
@Test
public void is_before_hurricane_season () {
LocalDate date = LocalDate.of(2014, Month.JANUARY, 02);
Boolean isHurricaneSeason = date.query(new HurricaneSeasonQuery());
assertFalse(isHurricaneSeason);
}
Is during hurricane season
@Test
public void is_during_hurricane_season () {
LocalDate date = LocalDate.of(2014, Month.JUNE, 30);
Boolean isHurricaneSeason = date.query(new HurricaneSeasonQuery());
assertTrue(isHurricaneSeason);
}
Is after hurricane season
@Test
public void is_after_hurricane_season () {
LocalDate date = LocalDate.of(2014, Month.DECEMBER, 30);
Boolean isHurricaneSeason = date.query(new HurricaneSeasonQuery());
assertFalse(isHurricaneSeason);
}