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).
All relevant classes are in the org.threeten.bp
package.
As you seem to care only about the date (day/month/year), I'm using org.threeten.bp.LocalDate
class. I also use the org.threeten.bp.temporal.IsoFields
class, which has fields that can properly deal with quarters:
// get today's date
LocalDate today = LocalDate.now();
// get previous quarter
LocalDate previousQuarter = today.minus(1, IsoFields.QUARTER_YEARS);
// get last day in previous quarter
long lastDayOfQuarter = IsoFields.DAY_OF_QUARTER.rangeRefinedBy(previousQuarter).getMaximum();
// get the date corresponding to the last day of quarter
LocalDate lastDayInPreviousQuarter = previousQuarter.with(IsoFields.DAY_OF_QUARTER, lastDayOfQuarter);
The lastDayInPreviousQuarter
will be 2017-06-30
.
The code above gets the current date in your system's default timezone, but if you want a more reliable code, you can tell the API to explicity uses one specific timezone, using the org.threeten.bp.ZoneId
class. In this example, I'm using mine (America/Sao_Paulo
), but you can change to the one that fits best to your system:
// get today's date in a specific timezone
ZoneId zone = ZoneId.of("America/Sao_Paulo");
LocalDate today = LocalDate.now(zone);
The API uses IANA timezones names (always in the format Region/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()
.
It's preferred to use an explicit timezone because the system's default can be changed without notice, even at runtime.
If you also need other fields (like hour, minutes, seconds, and so on), check this tutorial that explains all the new types. The tutorial is for Java 8, but the ThreeTen Backport has all the same classes and methods (just the package name is different: in Java 8 is java.time
and in ThreeTen Backport is org.threeten.bp
).