The solutions given so far will tell you 1, 2, 3, 4 or 5. But the question said that he wants to know the "last" and "the second to continue." If the questionnaire really needs to know the "last", etc., there is a bit more complicated. You must find out how many Sundays this month are to find out if the fourth Sunday is the last. The first way to understand what is happening to me is:
GregorianCalendar gc=new GregorianCalendar(); gc.setTime(mydate); gc.set(Calendar.DAY_OF_MONTH,1); // Roll back to first of month int weekday=gc.get(Calendar.DAY_OF_WEEK); // day of week of first day // Find day of month of first Sunday int firstSunday; if (weekday==Calendar.SUNDAY) firstSunday=1; else firstSunday=weekday-Calendar.SUNDAY+6; // Day of month of fifth Sunday, if it exists int fifthSunday=firstSunday+7*4; // Find last day of month gc.add(Calendar.MONTH,1); gc.add(Calendar.DATE,-1); int lastDay=gc.get(DAY_OF_MONTH); int sundays; if (fifthSunday<lastDay) sundays=4; else sundays=5;
This seems like a lot of work. Does anyone see an easier way?
source share