从键盘输入两个日期,格式如:2022-06-18。判断两个日期的先后,并输出它们之间间隔的天数、周数(不足一周按0计算)。java用到split(),parseInt()
时间: 2024-05-09 08:19:17 浏览: 152
```java
import java.util.Scanner;
public class DateComparison {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个日期(格式:yyyy-MM-dd):");
String date1Str = scanner.nextLine();
System.out.print("请输入第二个日期(格式:yyyy-MM-dd):");
String date2Str = scanner.nextLine();
String[] date1Arr = date1Str.split("-");
String[] date2Arr = date2Str.split("-");
int year1 = Integer.parseInt(date1Arr[0]);
int month1 = Integer.parseInt(date1Arr[1]);
int day1 = Integer.parseInt(date1Arr[2]);
int year2 = Integer.parseInt(date2Arr[0]);
int month2 = Integer.parseInt(date2Arr[1]);
int day2 = Integer.parseInt(date2Arr[2]);
int days;
if (year1 < year2 || (year1 == year2 && month1 < month2) || (year1 == year2 && month1 == month2 && day1 < day2)) {
days = getDaysBetween(year1, month1, day1, year2, month2, day2);
System.out.println(date1Str + " 在 " + date2Str + " 之前,间隔 " + days + " 天," + days / 7 + " 周。");
} else if (year1 > year2 || (year1 == year2 && month1 > month2) || (year1 == year2 && month1 == month2 && day1 > day2)) {
days = getDaysBetween(year2, month2, day2, year1, month1, day1);
System.out.println(date1Str + " 在 " + date2Str + " 之后,间隔 " + days + " 天," + days / 7 + " 周。");
} else {
System.out.println(date1Str + " 和 " + date2Str + " 是同一天。");
}
}
private static int getDaysBetween(int year1, int month1, int day1, int year2, int month2, int day2) {
int days = 0;
while (year1 < year2 || month1 < month2 || day1 < day2) {
days++;
day1++;
if (day1 > getDaysOfMonth(year1, month1)) {
day1 = 1;
month1++;
if (month1 > 12) {
month1 = 1;
year1++;
}
}
}
return days;
}
private static int getDaysOfMonth(int year, int month) {
switch (month) {
case 2:
return isLeapYear(year) ? 29 : 28;
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}
}
private static boolean isLeapYear(int year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
}
```
注:以上代码中用到了 isLeapYear() 方法判断闰年,getDaysOfMonth() 方法获取某年某月的天数,getDaysBetween() 方法计算两个日期间隔的天数。
阅读全文