Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last Sunday before current date? [duplicate]

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?

like image 642
malcoauri Avatar asked Oct 08 '12 13:10

malcoauri


4 Answers

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.

like image 195
Grzegorz Gajos Avatar answered Nov 17 '22 20:11

Grzegorz Gajos


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.

like image 20
Jimmy Avatar answered Nov 17 '22 20:11

Jimmy


You could iterate back in steps of one day until you arrive on a Sunday:

Calendar cal = Calendar.getInstance();
while (cal.get( Calendar.DAY_OF_WEEK ) != Calendar.SUNDAY)
    cal.add( Calendar.DAY_OF_WEEK, -1 );

or, in only one step, substract the difference in days between sunday and now:

Calendar cal = Calendar.getInstance();
int dayOfTheWeek = cal.get( Calendar.DAY_OF_WEEK );
cal.add( Calendar.DAY_OF_WEEK, Calendar.SUNDAY - dayOfTheWeek );
like image 30
dapek Avatar answered Nov 17 '22 20:11

dapek


final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(cal.getTimeInMillis() //
     // Saturday is the 7th day of week, so use modulo to get it : remove day between todoay
     - (( cal.get(Calendar.DAY_OF_WEEK) % 7) * 86400000)); // 86400000=24*60*60*1000

System.out.println(cal.getTime());
. . .
like image 44
cl-r Avatar answered Nov 17 '22 22:11

cl-r