I have the following code for getting the last Sunday before the current date:
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR, cale
Here's how to do it with a Kotlin extension and the Joda Time library.
Answer is based on linqu's answer but this also fixes a bug in that answer.
The bug was that it did not work if the current date was the same day you're trying to get.
/**
* E.g., DateTimeConstants.SUNDAY
*/
fun DateTime.previousDayOfWeek(day: Int): DateTime {
var date = this
if(date.dayOfWeek == day) date = date.minusDays(1)
val offset = (date.dayOfWeek - day + 7) % 7
return date.minusDays(offset)
}
fun DateTime.previousSunday(): DateTime {
return previousDayOfWeek(DateTimeConstants.SUNDAY)
}