How to get the last Sunday before current date?
java.time.temporal.TemporalAdjuster
This can be easily achieved by a TemporalAdjuster
implementation found in TemporalAdjusters
along with the DayOfWeek
enum. Specifically, previous(DayOfWeek dayOfWeek)
.
LocalDate
.now()
.with(
TemporalAdjusters.previous( DayOfWeek.SUNDAY )
) ;
If today is Sunday and you would like the result to be today rather than a week ago, call previousOrSame(DayOfWeek dayOfWeek)
.
LocalDate
.now()
.with(
TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY )
) ;
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.
This will work. We first get the day count, and then subtract that with the current day and add 1 ( for sunday)
Calendar cal=Calendar.getInstance();
cal.add( Calendar.DAY_OF_WEEK, -(cal.get(Calendar.DAY_OF_WEEK)-1));
System.out.println(cal.get(Calendar.DATE));
Edit : As pointed out by Basil Bourque in the comment, see the answer by Grzegorz Gajos for Java 8 and later.