Although you can do the math by yourself (as the other answers are already covering), you could consider using the new date/time API.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time
and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp
), but the classes and methods names are the same.
The code is straightforward:
// current date
LocalDate now = LocalDate.now();
// get quarter
int presentQuarter = now.get(IsoFields.QUARTER_OF_YEAR);
// year for last quarter
int year = now.minus(1, IsoFields.QUARTER_YEARS).getYear();
LocalDate
is in java.time
or org.threeten.bp
package, and IsoFields
is in java.time.temporal
or org.threeten.bp.temporal
(depending on whether you're using Java 8 or ThreeTen Backport).
I'm using LocalDate.now()
, which gets the current date using the system's default timezone, but it's better to always make explicit what timezone you're using (even it you use the default):
// use system default timezone
LocalDate now = LocalDate.now(ZoneId.systemDefault());
But the system's default timezone can change (even at runtime), so it's even better to explicit one by name:
// current date using an explicit timezone name
LocalDate now = LocalDate.now(ZoneId.of("Europe/London"));
The API uses IANA timezones names (always in the format Continent/City
, like America/Sao_Paulo
or Europe/Berlin
).
Avoid using the 3-letter abbreviations (like CST
or PST
) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds()
.