Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get last thursday of month in java [duplicate]

Tags:

java

groovy

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))

like image 385
AMAN KUMAR Avatar asked Dec 15 '15 11:12

AMAN KUMAR


1 Answers

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.

like image 194
assylias Avatar answered Sep 19 '22 14:09

assylias