设int year,month,day分别表示一个日期中的年月日,试编程求 a)对于任意三个整数,判断其是否为一个合法的日期值。 b)给定一个日期值,计算若干天后的日期值 如果有两个日期值,计算他们相距的天数。请用java写
时间: 2024-05-12 07:15:00 浏览: 98
a)判断日期是否合法的Java代码:
```java
public static boolean isValidDate(int year, int month, int day) {
if (month < 1 || month > 12) {
return false;
}
int maxDay = 31;
if (month == 4 || month == 6 || month == 9 || month == 11) {
maxDay = 30;
} else if (month == 2) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
maxDay = 29;
} else {
maxDay = 28;
}
}
if (day < 1 || day > maxDay) {
return false;
}
return true;
}
```
b)计算若干天后的日期值的Java代码:
```java
public static void calculateDateAfter(int year, int month, int day, int days) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, day);
calendar.add(Calendar.DATE, days);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
String dateStr = sdf.format(calendar.getTime());
System.out.println("计算后的日期为:" + dateStr);
}
```
c)计算两个日期相差的天数的Java代码:
```java
public static int calculateDaysBetween(int year1, int month1, int day1, int year2, int month2, int day2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.set(year1, month1 - 1, day1);
Calendar calendar2 = Calendar.getInstance();
calendar2.set(year2, month2 - 1, day2);
long time1 = calendar1.getTimeInMillis();
long time2 = calendar2.getTimeInMillis();
long betweenDays = (time2 - time1) / (1000 * 3600 * 24);
return (int) betweenDays;
}
```
阅读全文