使用java实现以下要求:输入年月日,输出距今天还有多少天,星期几,是否为公历节日
时间: 2023-06-24 19:06:38 浏览: 48
以下是使用Java实现输入年月日,输出距今天还有多少天,星期几,是否为公历节日的代码:
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Main {
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();
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, day);
Date date = calendar.getTime();
Date now = new Date();
long diff = Math.abs(date.getTime() - now.getTime());
long days = diff / (1000 * 60 * 60 * 24);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
String week = sdf.format(date);
boolean isHoliday = isHoliday(month, day);
System.out.println("距今天还有" + days + "天,星期" + week + "," + (isHoliday ? "是公历节日" : "不是公历节日"));
}
private static boolean isHoliday(int month, int day) {
if (month == 1 && day == 1) {
return true;
} else if (month == 2 && day == 14) {
return true;
} else if (month == 3 && day == 8) {
return true;
} else if (month == 5 && day == 1) {
return true;
} else if (month == 6 && day == 1) {
return true;
} else if (month == 10 && day == 1) {
return true;
} else if (month == 12 && day == 25) {
return true;
} else {
return false;
}
}
}
```
代码解释如下:
1. 首先,我们使用Scanner类从控制台读入年月日。
2. 接着,我们使用Calendar类将输入的年月日转换为一个Date对象,并获取当前时间的Date对象。
3. 然后,我们计算两个日期之间的天数差,并使用SimpleDateFormat类获取日期是星期几。
4. 最后,我们使用一个自定义的isHoliday()方法判断日期是否为公历节日。
isHoliday()方法中的判断条件是根据公历节日的日期来确定的。例如,元旦节是1月1日,情人节是2月14日,妇女节是3月8日,劳动节是5月1日,儿童节是6月1日,国庆节是10月1日,圣诞节是12月25日。如果输入的日期与这些日期相同,则判断为公历节日。