How to get the last Sunday before current date?

2020-06-08 03:24发布

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?

7条回答
霸刀☆藐视天下
2楼-- · 2020-06-08 04:18

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 );
查看更多
登录 后发表回答