I have the following code for getting the last Sunday before the current date:
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR)-1);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
Log.e("first day", String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)));
But this code doesn't work. Please, tell me, how can I fix it?
java.time.temporal.TemporalAdjuster
This can be easily achieved by a
TemporalAdjuster
implementation found inTemporalAdjusters
along with theDayOfWeek
enum. Specifically,previous(DayOfWeek dayOfWeek)
.If today is Sunday and you would like the result to be today rather than a week ago, call
previousOrSame(DayOfWeek dayOfWeek)
.These classes are built into Java 8 and later, and built into Android 26 and later. For Java 6 & 7, most of the functionality is back-ported in ThreeTen-Backport. For earlier Android, see ThreeTenABP.
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.
The following works for me irrespective of which month and year.
Here is a snippet to calculate any last day of the week with Joda:
Just replace
DateTimeConstants.THURSDAY
with your day of choice.This will work. We first get the day count, and then subtract that with the current day and add 1 ( for sunday)
Edit : As pointed out by Basil Bourque in the comment, see the answer by Grzegorz Gajos for Java 8 and later.