How to get the last Sunday before current date?

后端 未结 7 1190
花落未央
花落未央 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 15:55

    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.

提交回复
热议问题