tl;dr
YearMonth.of( 2015 , Month.NOVEMBER ) // Represent the entirety of a specified month.
.atEndOfMonth() // Get the date of the last day of that month.
.with( TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY ) ) // Move to the previous Sunday, or keep if already Sunday.
Avoid legacy date-time classes
The Question and other Answers are outmoded, using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Use smart objects, not dumb primitives
Rather than pass year and month as mere integers, pass a single argument of YearMonth
class. Doing so ensures valid values, makes your code more self-documenting, and provides type-safety.
YearMonth ym = YearMonth.of( 2015 , Month.NOVEMBER ) ; // Or YearMonth.of( 2015 , 11 ) with sane numbering for month 1-12 for January-December.
The LocalDate
class represents a date-only value without time-of-day and without time zone.
Get the last day of the month.
LocalDate endOfMonth = ym.atEndOfMonth() ;
Find the previous Sunday, or keep the end-of-month if it is already a Sunday. Use a TemporalAdjuster
found in the TemporalAdjusters
class.
LocalDate lastSundayOfPriorMonth = endOfMonth.with( TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY ) ) ;
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.
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.