【代码】将日期以“周”划分

从当前开始,记录五个周一是哪一天

        /** Part 1 -- 日期处理
         执行代码结束后获得:
         fourweek[4] 四周的周一的日期 类型为int 格式为:20200430
         */
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); // 日期格式
        int dayOfWeek = (calendar.get(Calendar.DAY_OF_WEEK) - 1);   //获取当前系统 周几
        int currentYear = calendar.get(Calendar.YEAR); //获取当前系统年份
        int currentMonth = calendar.get(Calendar.MONTH) + 1;//获取当前系统月份
        int currentDay = calendar.get(Calendar.DAY_OF_MONTH);//获取系统当前日期
        int diff = currentDay - dayOfWeek + 1; //还需要一些别的东西 比如 月份的判断等
        int nearlyYMonday = 0;  // 距离现在最近的上一个周一的年
        int nearlyMMonday = 0;  // 月
        int nearlyDMonday = 0;  // 日
        int[] fourWeek = new int[5];
        int zbc = 0; // 循环变量
        if (diff > 0) {//如果今天的日期大于周几,也就是说最近的周一在本月
            nearlyYMonday = currentYear;
            nearlyMMonday = currentMonth;
            nearlyDMonday = diff;
        } else {
            // diff <= 0 那么日期应该向上个月调整几天
            if (currentMonth >= 1) {
                nearlyYMonday = currentYear;
                nearlyMMonday = currentMonth - 1;
                nearlyDMonday = hmds(currentYear, currentMonth - 1) + diff;
            } else {
                nearlyYMonday = currentYear - 1;
                nearlyMMonday = 12;
                nearlyDMonday = hmds(currentYear - 1, 12) + diff;
            }
        }
        int temporaryYear = nearlyYMonday;   //临时年
        int temporaryMonth = nearlyMMonday;   //临时月
        int temporaryDay = nearlyDMonday;   //临时日

        fourWeek[4] = nearlyYMonday * 10000 + nearlyMMonday * 100 + nearlyDMonday;
        for (zbc = 3; zbc >= 0; zbc--) {
            if (temporaryDay > 7) {
                temporaryDay -= 7;
            }else if (temporaryMonth == 1 && temporaryDay <= 7) {
                temporaryYear = temporaryYear - 1;
                temporaryMonth = 12;
                temporaryDay = 24 + nearlyDMonday;
            }else if (temporaryMonth != 1 && temporaryDay <= 7) {
                temporaryMonth -= 1;
                temporaryDay = hmds(temporaryYear, temporaryMonth - 1) - 7 + nearlyDMonday;
            }
            fourWeek[zbc]  = temporaryYear * 10000 + temporaryMonth * 100 + temporaryDay;
        }
}


你可能感兴趣的:(Java,java)