tl;dr
YearMonth.now().minusMonths( 1 ).atEndOfMonth() // or .atDay( 1 )
Details
Get today’s date.
ZoneId z = ZoneId.of( “Africa/Tunis” ) ;
LocalDate today = LocalDate.now( z ) ;
Get the year-month of that date.
YearMonth ymCurrent = YearMonth.from( today ) ;
Add the ThreeTen-Extra library to your project to access the LocalDateRange
class. This class represents as one object a pair of LocalDate
objects, start date and stop date, for a date range from one date to the other date.
LocalDateRange rangeCurrent = LocalDateRange.ofClosed( ymCurrent.atDay( 1 ) , today ) ;
Move to previous month.
YearMonth ymPrevious = ymCurrent.minusMonths( 1 ) ;
LocalDateRange rangePrevious = LocalDateRange.ofClosed( ymPrevious.atDay( 1 ) , ymPrevious.atEndOfMonth() ) ;
Subtract yet another time for your third month.
Tip: Consider using the Half-Open approach to defining a span of time, where the beginning is inclusive while the ending is exclusive. So a month starts with the first day of the month and runs up to, but does not include, the first day of the following month.
For another valid approach using java.time classes, see the Answer by diston.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.