Given an instance of java.util.Date
which is a Sunday. If there are 4 Sundays in the month in question, I need to figure out whether the chosen date is
If there are 5 Sundays in the month in question, then I need to figure out whether the chosen date is
I've had a look in JodaTime, but haven't found the relevant functionality there yet. The project is actually a Groovy project, so I could use either Java or Groovy to solve this.
Thanks, Donal
Solutions given so far will tell you 1st, 2nd, 3rd, 4th, or 5th. But the question said he wanted to know "last" and "second to last". If the questioner really needs to know "last" etc, there's a little extra complexity. You have to figure out how many Sundays are in the month to know whether or not the 4th Sunday is the last. The first way to figure that out that occurs 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;
That seems like rather a lot of work. Anybody see an easier way?
DAY_OF_WEEK_IN_MONTH
import java.sql.Date;
import java.util.Calendar;
public class Dow {
public static void main(String[] args) {
Date date = new Date( 2010, 4, 1 );
Calendar cal = Calendar.getInstance();
cal.setTime( date );
for ( int week = 0 ; week < 5 ; week++ ) {
System.out.println( cal.getTime() + " week:" + cal.get( Calendar.DAY_OF_WEEK_IN_MONTH ) );
cal.add( Calendar.WEEK_OF_MONTH, 1 );
}
}
}
> Sun May 01 00:00:00 CEST 3910 week:1
> Sun May 08 00:00:00 CEST 3910 week:2
> Sun May 15 00:00:00 CEST 3910 week:3
> Sun May 22 00:00:00 CEST 3910 week:4
> Sun May 29 00:00:00 CEST 3910 week:5
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