6

I have to fetch date of last Thursday of month of any year but the problem I'm facing is that for the month of dec'15 last thursday is 31-dec-2015 but I'm getting 24-dec-2015 for the following code:

Date getLastThursday(def month, def year ) {
    Calendar cal = Calendar.getInstance();
    cal.set( year, month,1 )
    cal.add( Calendar.DAY_OF_MONTH, -(cal.get(Calendar.DAY_OF_WEEK )%7+2) );
    return cal.getTime();
}

And also explain me how this line of code internally works?

cal.add(Calendar.DAY_OF_MONTH, -(cal.get(Calendar.DAY_OF_WEEK )%7+2))

AMAN KUMAR
  • 277
  • 1
  • 6
  • 19

2 Answers2

10

If you use Java 8+, you can use a temporal adjuster (part of the Java Time API):

int month = 12;
int year = 2015;
LocalDate lastThursday = LocalDate.of(year, month, 1).with(lastInMonth(THURSDAY));
System.out.println("lastThursday = " + lastThursday); //prints 2015-12-31

Note: requires static imports

import static java.time.DayOfWeek.THURSDAY;
import static java.time.temporal.TemporalAdjusters.lastInMonth;

If you can't use the new API, I suspect the problem is in the modulus operation and this should work:

//month should be 0-based, i.e. use 11 for December
static Date getLastThursday(int month, int year) {
  Calendar cal = Calendar.getInstance();
  cal.set(year, month + 1, 1);
  cal.add(Calendar.DAY_OF_MONTH, -((cal.get(Calendar.DAY_OF_WEEK) + 2) % 7));
  if (cal.get(Calendar.MONTH) != month) cal.add(Calendar.DAY_OF_MONTH, -7);
  return cal.getTime();
}

The second if condition is there to make sure we have gone back one month.

assylias
  • 321,522
  • 82
  • 660
  • 783
-1

Just put your modulus % outside:

cal.add( Calendar.DAY_OF_MONTH, -(cal.get(Calendar.DAY_OF_WEEK )+2)%7 );

if not, you get -8 => 24 december

and use month+1