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