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;
}
}
}
- 相较于网络上经典流传的Switch-Case思路,这里换了种实现方法,尽可能的达到不臃肿,热爱逆向的人想必对其也是爱恨交加吧!
君可见,此处应用了反射,我学Java的日子也并不长,但我觉得就是要敢于去尝试,勇于付诸实践 - 写在章末:有兴趣的可以去了解蔡勒公式以及基姆拉尔森公式,也是比较有意思
问:为啥出来写<水(bushi)>这篇文章?
答:与万能的群友交流来的灵感,嗯。