java.time
java.time, the modern Java data and time API, gives you most of what you are asking for. Only it dies not know your financial year. The quarter you are asking for is one less that the quarter used in the ISO calendar system supported by java.time. So my trick is to subtract one quarter from your date and then query java.time about the quarter and year. That will give you the numbers you require.
In code, trying different dates:
LocalDate[] exampleDates = {
LocalDate.of(2020, Month.JANUARY, 1),
LocalDate.of(2020, Month.JUNE, 30),
LocalDate.of(2020, Month.AUGUST, 22),
LocalDate.of(2020, Month.OCTOBER, 1),
LocalDate.of(2021, Month.MARCH, 31),
};
for (LocalDate date : exampleDates) {
LocalDate syntheticQuarterDate = date.minus(1, IsoFields.QUARTER_YEARS);
// Get quarter number and year as int
int quarter = syntheticQuarterDate.get(IsoFields.QUARTER_OF_YEAR);
int year = syntheticQuarterDate.getYear();
System.out.format("Quarter: %d; year: %d%n", quarter, year);
}
Output is:
Quarter: 4; year: 2019
Quarter: 1; year: 2020
Quarter: 2; year: 2020
Quarter: 3; year: 2020
Quarter: 4; year: 2020
Suppose you wanted a string like Q42019
rather than the numbers. In this case it’s best to use a formatter:
DateTimeFormatter quarterFormatter
= DateTimeFormatter.ofPattern("QQQuuuu", Locale.ENGLISH);
Now for each date do:
// Print a string like "Q42019"
String quarterString = syntheticQuarterDate.format(quarterFormatter);
System.out.println(quarterString);
Output using the same dates as before:
Q42019
Q12020
Q22020
Q32020
Q42020
Question: Does that work with Java 7?
java.time works nicely on Java 7. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links