How to get the last Sunday before current date?

后端 未结 7 1374
花落未央
花落未央 2021-02-12 15:07

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         


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-12 16:00

    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 );
    

提交回复
热议问题