I want to get the last sunday of any given month, and its working to a point however on some inputs if the sunday is the first day of next month it shows that date instead of the same month's last week. Here is what
public static String getLastSunday(int month, int year) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, 1);
if (leap(year)) {
cal.add(Calendar.DAY_OF_MONTH, -(cal.get(Calendar.DAY_OF_WEEK) - 2));
} else {
cal.add(Calendar.DAY_OF_MONTH, -(cal.get(Calendar.DAY_OF_WEEK)%7 - 1));
}
return cal.getTime().toString().substring(0, 10);
}
calling the function as:
getLastSunday(10, 2015);
returns the output:
Sun Nov 01
Where did I go wrong? Also if it is the leap year, I am not sure if going from -1 to -2 is correct, I researched about it but couldnt find anything useful.
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.
The Question and other Answers are outmoded, using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
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 ) ) ;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With