java怎么获取本周一到周末时间

2024-11-30 06:48:44
推荐回答(1个)
回答(1):

/**
     * 获取上周五时间
     */
    public Date lastFirday() {
  //作用防止周日得到本周日期
        Calendar calendar = Calendar.getInstance();
        while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
            calendar.add(Calendar.DAY_OF_WEEK, -1);
        }
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        int offset = 7 - dayOfWeek;
        calendar.add(Calendar.DATE, offset - 9);
        return DateTimeUtil.getFirstDayOfWeek(calendar.getTime(), 6);//这是从上周日开始数的到本周五为6
    }
 
/**
     * 获取上周一时间
     */
    public Date lastMonday() {
        Calendar calendar = Calendar.getInstance();
        while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
            calendar.add(Calendar.DAY_OF_WEEK, -1);
        }
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        int offset = 1 - dayOfWeek;
        calendar.add(Calendar.DATE, offset - 7);
        return DateTimeUtil.getFirstDayOfWeek(calendar.getTime(), 2);
    }

参考
请采纳,谢谢