This example will show how to find the current quarter from a given date using java date and java 8 date time API TemporalQuery.
Straight up Java
@Test
public void current_quarter_with_java() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 3);
int month = cal.get(Calendar.MONTH);
int quarter = 0;
// 3, 6, 9, 12
if (month <= 3) {
quarter = 1;
} else if (month <= 6) {
quarter = 2;
} else if (month <= 9) {
quarter = 3;
} else {
quarter = 4;
}
assertEquals(1, quarter);
}
Java 8 Date and Time API
Java 8 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.MONTH_OF_YEAR 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.
@Test
public void current_quarter_with_java8() {
LocalDate date = LocalDate.of(2014, 02, 01);
Integer quarter = date.query(new Quarter());
assertEquals(new Integer(1), quarter);
}
/**
* Methods returns the proper quarter based on the date passed
*/
class Quarter implements TemporalQuery<Integer> {
@Override
public Integer queryFrom(TemporalAccessor date) {
int month = date.get(ChronoField.MONTH_OF_YEAR);
if (month <= 3) {
return new Integer(1);
} else if (month <= 6) {
return new Integer(2);
} else if (month <= 9) {
return new Integer(3);
} else {
return new Integer(4);
}
}
}