import java.util.Scanner;
public class MyCalendar {
//判断是否是闰年
public boolean isLeapYear(int year) {
return year % 4 == 0 && year % 100!=0 || year % 400 == 0;
}
//判断y年m月有多少天
public int getDaysOfMonth(int y,int m) {
switch(m) {
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
return isLeapYear(y) ? 29 : 30;
default:
return 31;
}
}
//距1900年过了多少天
public int getTotalDaysFrom1900(int y, int m) {
int day = 0;
for (int i = 1900; i < y; i++) {
int d = isLeapYear(i) ? 366 : 365;
day += d;
}
for (int j = 1; j < m; j++) {
day += getDaysOfMonth(y, j);
}
return day;
}
//两个日期相距多少天
public int getTotalDays(int a, int b, int c ,int y, int m ,int d) {
int days = 0;
days += getDaysOfMonth(a, b) - c;
for (int j = b+1; j <= 12; j++) {
days += getDaysOfMonth(a, j);
}
for (int i = a+1; i < y; i++) {
days += isLeapYear(i) ? 366 : 365;
}
for (int j = 1; j < m; j++) {
days += getDaysOfMonth(y, j);
}
days += d;
return days;
}
//打印日历
public void printCalendar(int y, int m) {
//获取打印日历前预留的空格数
int space = getTotalDaysFrom1900(y, m) % 7;
//获取目标年份月份
int days = getDaysOfMonth(y,m);
System.out.println("===============万年历【"+y+"】年"+"【"+m+"】月"+"=============");
System.out.println("一\t二\t三\t四\t五\t六\t日");
System.out.println("====================================================");
int count = 0;
for (int i = 0; i < space; i++) {
System.out.print("\t");
count++;
}
for (int i = 1; i <= days; i++) {
count++;
System.out.print(i + "\t");
if(count == 7) {
System.out.println();
count = 0;
}
}
System.out.println();
System.out.println("====================================================");
}
public static void main(String[] args) {
MyCalendar mc = new MyCalendar();
boolean b = mc.isLeapYear(2019);
System.out.println(b ? "是闰年" : "不是闰年");
int days = mc.getDaysOfMonth(2020, 2);
System.out.println(days);
int t = mc.getTotalDaysFrom1900(2020, 11);
System.out.println(t);
//你活了多少天
Scanner sc = new Scanner(System.in);
int year, month, day;
int ay, am, ad;
System.out.println("请输入你的出生日期:");
ay = sc.nextInt();
am = sc.nextInt();
ad = sc.nextInt();
System.out.println("请输入现在的年月日:");
year = sc.nextInt();
month = sc.nextInt();
day = sc.nextInt();
int c = mc.getTotalDays(ay, am, ad, year, month, day);
System.out.println(c);
int y = sc.nextInt();
int m = sc.nextInt();
mc.printCalendar(y, m);
sc.close();
}
}
【Java】日历打印及两个日期相距多少天
最新推荐文章于 2023-02-15 12:02:44 发布