Java使用蔡勒公式快速计算某一天是星期几

版权声明:知识诚无价,分享价更高。 https://blog.csdn.net/u013955940/article/details/82692378

使用蔡勒公式,只需给出年月日,就可以用该公式来计算任意一个日期是星期几。

请参考以下计算星期几的代码例子:

/**
 * 蔡勒公式Java实现例子
 * @author Zebe
 * @version 1.0.0
 */
public class ZellerDemo {

    /**
     * 根据蔡勒公式计算任意一个日期是星期几
     * @param year  年
     * @param month 月
     * @param day   日
     */
    public static void calcWeekByZeller(int year, int month, int day) {
        int x = year;
        int y = month;
        int z = day;
        if (month == 1) {
            month = 13;
            year = year - 1;
        }
        if (month == 12) {
            month = 14;
            year = year - 1;
        }
        // 蔡勒公式
        int h = ((day + (26 * (month + 1) / 10) + (year % 100) + ((year % 100) / 4) + ((year / 100) / 4) + 5 * (year / 100)) % 7);
        switch (h) {
            case 0:
                System.out.println(x + "年" + y + "月" + z + "日: 星期六");
                break;
            case 1:
                System.out.println(x + "年" + y + "月" + z + "日: 星期天");
                break;
            case 2:
                System.out.println(x + "年" + y + "月" + z + "日: 星期一");
                break;
            case 3:
                System.out.println(x + "年" + y + "月" + z + "日: 星期二");
                break;
            case 4:
                System.out.println(x + "年" + y + "月" + z + "日: 星期三");
                break;
            case 5:
                System.out.println(x + "年" + y + "月" + z + "日: 星期四");
                break;
            case 6:
                System.out.println(x + "年" + y + "月" + z + "日: 星期五");
                break;
            default:
                System.err.println("公式可能写错了,或者日期不合法");
        }
    }

    /**
     * 程序入口
     * @param args 运行参数
     */
    public static void main(String[] args) {
        calcWeekByZeller(2017, 5, 7); // 周日
    }

}

本文首发于个人独立博客,文章链接:http://www.zebe.me/java-zeller-formula

猜你喜欢

转载自blog.csdn.net/u013955940/article/details/82692378