java代码获取本周的开始日期和结束日期,并动态获取前几周的或者后几周的开始日期和结束日期。

/**
     * @param deltaWeeks 相对于当前位置的前几周或者后几周
     */
    public void getWeekBeginDateAndEndDate(int deltaWeeks) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_YEAR, deltaWeeks * 7);
        int currentDay = calendar.get(Calendar.DAY_OF_WEEK);
        if (currentDay == 1) {
            currentDay = 7;
        } else {
            currentDay = currentDay - 1;
        }
        calendar.add(Calendar.DAY_OF_YEAR, 1 - currentDay);
        Date date = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(format.format(date));
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_YEAR, 6);
        System.out.println(format.format(calendar.getTime()));
    }

以上代码经过测试,可用无bug。

猜你喜欢

转载自blog.csdn.net/Always_MyHomeTown/article/details/83413393