java获取当前时间的前三几个节假日
时间: 2023-06-30 22:14:39 浏览: 164
为了获取当前时间的前三个节假日,需要先获取当前时间,然后根据国家法定节假日的日期计算出所有节假日的日期,最后筛选出前三个离当前时间最近的节假日日期即可。下面是一个 Java 的示例代码:
```java
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
public class HolidayFinder {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now(); // 获取当前日期
List<LocalDate> holidays = new ArrayList<>(); // 存储所有节假日日期的列表
// 计算所有节假日的日期并添加到列表中
holidays.add(LocalDate.of(currentDate.getYear(), 1, 1)); // 元旦
holidays.add(LocalDate.of(currentDate.getYear(), 5, 1)); // 劳动节
holidays.add(LocalDate.of(currentDate.getYear(), 10, 1)); // 国庆节
// 如果当前时间已经过了今年的某个节假日,就要计算明年的该节假日日期
if (currentDate.isAfter(holidays.get(0))) {
holidays.set(0, holidays.get(0).plusYears(1));
}
if (currentDate.isAfter(holidays.get(1))) {
holidays.set(1, holidays.get(1).plusYears(1));
}
if (currentDate.isAfter(holidays.get(2))) {
holidays.set(2, holidays.get(2).plusYears(1));
}
// 排序所有节假日日期,离当前时间最近的节假日排在前面
holidays.sort((a, b) -> (int) ChronoUnit.DAYS.between(currentDate, a) - (int) ChronoUnit.DAYS.between(currentDate, b));
// 输出前三个节假日的日期
for (int i = 0; i < 3; i++) {
System.out.println(holidays.get(i));
}
}
}
```
这个程序会输出当前时间的前三个节假日的日期,例如今天是 2022 年 7 月 10 日,输出结果可能是:
```
2023-01-01
2023-05-01
2022-10-01
```
这表示距离当前时间最近的三个节假日是 2023 年的元旦、劳动节和 2022 年的国庆节。
阅读全文
相关推荐
















