编程语言爱好者算法编程Java

Java实现计算日期(模拟)

2023-06-13  本文已影响0人  binx6

插句题外话先,关于蔡勒公式,网上众说纷纭,这里就不再一一赘述

import java.lang.reflect.Method;
import java.util.*;


public class Main {
    /**
    * @author: binx6
    * @last-edit-date: 2023.06.14
    */
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年份:");
int year = scanner.nextInt();
System.out.print("请输入月份:");
int month = scanner.nextInt();
System.out.print("请输入日期:");
int day = scanner.nextInt();


    // 判断该年份是否为闰年
    boolean isLeapYear = isLeapYear(year);

    // 判断该月份是否存在
    boolean isMonthValid = isMonthValid(month);

    // 判断该日期是否存在
    boolean isDayValid = isDayValid(year, month, day);

    if (isLeapYear && month == 2 && day == 29) {
        System.out.println(year + "年是闰年,2月29日是存在的");
    } else if (isMonthValid && isDayValid) {
        int week = getWeekday(year, month, day);
        System.out.println(year + "年" + month + "月" + day + "日是星期" + week);
    } else if (!isMonthValid) {
        System.out.println("年份不存在" + month + "月,请重新输入");
    } else if (!isDayValid) {
        System.out.println(year + "年" + month + "月不存在" + day + "日");
    }
}

public static int getWeekday(int year, int month, int day) {
    int[] monthTable = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
    if (month < 3) {
        year--;
    }
    int week = (year + year / 4 - year / 100 + year / 400 + monthTable[month - 1] + day) % 7;
    if (week == 0) {
        week = 7;
    }
    // 假如计算出来的星期几不正确,就将日期往前或往后调整(纠偏)
    if (week != getDayOfWeek(year, month, day)) {
        if (week < getDayOfWeek(year, month, day)) {
            // 往后调整
            day++;
        } else {
            // 往前调整
            day--;
        }
    }
    return week;
}

public static int getDayOfWeek(int year, int month, int day) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, month - 1, day);
    return cal.get(Calendar.DAY_OF_WEEK);
}

public static boolean isLeapYear(int year) {
    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
        return true;
    }
    return false;
}

public static boolean isMonthValid(int month) {
    try {
        Method method = Calendar.class.getDeclaredMethod("getActualMaximum", int.class);
        Calendar cal = Calendar.getInstance();
        method.invoke(cal, Calendar.MONTH);
        if (month < 1 || month > 12) {
            return false;
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

public static boolean isDayValid(int year, int month, int day) {
    try {
        Method method = Calendar.class.getDeclaredMethod("getActualMaximum", int.class);
        Calendar cal = Calendar.getInstance();
        int maxDay = (int) method.invoke(cal, Calendar.DAY_OF_MONTH);
        if (day < 1 || day > maxDay) {
            return false;
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

}
上一篇 下一篇

猜你喜欢

热点阅读