What is the best way to retrieve the dates for last Monday and Friday

前端 未结 4 1827
南方客
南方客 2020-12-31 10:23

I need to get the dates for Monday and Friday last week. To do this, i am getting the date of Monday this week and subtracting 7 days. This gives me the date for Monday last

4条回答
  •  被撕碎了的回忆
    2020-12-31 11:23

    You still have start of week set to sunday, which means that Calendar.MONDAY on a saturday is the monday before, while Calendar.MONDAY on a sunday is the next day.

    What you need to do is (according to how you want it according to your comment above), to set the start of week to monday.

    Calendar cal = Calendar.getInstance();
    cal.setFirstDayOfWeek(Calendar.MONDAY);
    
    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    cal.add(Calendar.DAY_OF_WEEK, -7); 
    ...
    

    Beyond that, and that the last second of friday isn't included in the range, your logic seems sound, and shouldn't have trouble with leap years/DST shifts etc.

提交回复
热议问题