获取某月份第一个周几算法(java)

public String GetMonthFirstFriday(int year, int month) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal_1 = Calendar.getInstance();//获取当前日期
        cal_1.set(year, month - 1, 1);
        //周几参数
        int weekNumber = 5;
        //本月第一天周几
        int y = calculateWeekDay(cal_1.getTime());
        if (y == 0) y = 7;
        if (y != weekNumber) {
            if (y > weekNumber) {
                cal_1.set(Calendar.DAY_OF_MONTH, weekNumber + (7 - y) + 1);
            } else {
                cal_1.set(Calendar.DAY_OF_MONTH, weekNumber + 1 - y);
            }
        }
        String s1 = format.format(cal_1.getTime());
        return String.format("%s年%s月第一个周五是:%s", year, month, s1);
    }
 private int calculateWeekDay(Date weekDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(weekDate);

        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DATE);

        if (month == 1 || month == 2) {
            month += 12;
            year--;
        }
        int weekCalculate = (day + 2 * month + 3 * (month + 1) / 5 + year + year / 4 - year / 100 + year / 400 + 1) % 7;
        //从周日:0开始,
        return weekCalculate;
    }

输入:2023,11

输出:2023年11月第一个周五是:2023-11-03

posted @ 2022-08-02 10:01  Shapley  阅读(366)  评论(0编辑  收藏  举报