This example uses a custom TemporalQuery to find the quarter of year for a given date. Implementing the TemporalQuery interface with the queryFrom(TemporalAccessor) method allows for a way to extract information from a temporal object. The queryFrom method compares the passed-in date against the ChronoField.MONTHOFYEAR then returning the appropriate quarter of year.
Note: This example is purely for demonstration as the java 8 time api provides YearMonth.from(temporal).get(IsoFields.QUARTER_OF_YEAR)
to get the current quarter of year.
Setup
public class CurrentQuarterQuery implements TemporalQuery<Integer> {
/*
* (non-Javadoc)
* @see java.time.temporal.TemporalQuery#queryFrom(java.time.temporal.TemporalAccessor)
*/
@Override
public Integer queryFrom(TemporalAccessor date) {
int month = date.get(ChronoField.MONTH_OF_YEAR);
if (month <= Month.MARCH.getValue()) {
return new Integer(1);
} else if (month <= Month.JUNE.getValue()) {
return new Integer(2);
} else if (month <= Month.SEPTEMBER.getValue()) {
return new Integer(3);
} else {
return new Integer(4);
}
}
}
First quarter
@Test
public void validate_first_quarter () {
LocalDate date = LocalDate.of(2014, Month.MARCH, 4);
Integer quarter = date.query(new CurrentQuarterQuery());
assertEquals(new Integer(1), quarter);
}
Second quarter
@Test
public void validate_second_quarter () {
LocalDate date = LocalDate.of(2014, Month.MAY, 8);
Integer quarter = date.query(new CurrentQuarterQuery());
assertEquals(new Integer(2), quarter);
}
Third quarter
@Test
public void validate_third_quarter () {
LocalDate date = LocalDate.of(2014, Month.SEPTEMBER, 2);
Integer quarter = date.query(new CurrentQuarterQuery());
assertEquals(new Integer(3), quarter);
}
Fourth quarter
@Test
public void validate_fourth_quarter () {
LocalDate date = LocalDate.of(2014, Month.DECEMBER, 18);
Integer quarter = date.query(new CurrentQuarterQuery());
assertEquals(new Integer(4), quarter);
}