导入maven依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.20</version>
</dependency>
定义常量类
public class HolidayConstant {
public final static String NEWYEARDAY = "元旦节";
public final static String CHINESENEWYEARGREGORIANFESTIVAL = "春节";
public final static String QINGMINGFESTIVAL = "清明节";
public final static String LABORDAY = "劳动节";
public final static String DRAGONBOATGREGORIANFESTIVAL = "端午节";
public final static String MIDAUTUMNGREGORIANFESTIVAL = "中秋节";
public final static String NATIONALDAY = "国庆节";
}
获取节日的类
import cn.hutool.core.date.ChineseDate;
import cn.hutool.core.date.DateUtil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
public class HolidayUtil {
public static Date getHoliday(String holidayName, int year) {
switch (holidayName) {
case HolidayConstant.NEWYEARDAY:
return DateUtil.parse(year + "-1-1");
case HolidayConstant.CHINESENEWYEARGREGORIANFESTIVAL:
ChineseDate chinesenewYearFestival = new ChineseDate(year, 1, 1);
return chinesenewYearFestival.getGregorianDate();
case HolidayConstant.QINGMINGFESTIVAL:
int param = year - 2000;
int qingmingDay = (int) (param * 0.2422 + 4.81) - param / 4;
return DateUtil.parse(year + "-4-" + qingmingDay);
case HolidayConstant.LABORDAY:
return DateUtil.parse(year + "-5-1");
case HolidayConstant.DRAGONBOATGREGORIANFESTIVAL:
ChineseDate dragonBoatFestival = new ChineseDate(year, 5, 5);
return dragonBoatFestival.getGregorianDate();
case HolidayConstant.MIDAUTUMNGREGORIANFESTIVAL:
ChineseDate midAutumnFestival = new ChineseDate(year, 8, 15);
return midAutumnFestival.getGregorianDate();
case HolidayConstant.NATIONALDAY:
return DateUtil.parse(year + "-10-1");
default:
return new Date();
}
}
}
测试
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
public class TestDome {
public static void main(String[] args) {
HolidayUtil holidayUtil=new HolidayUtil();
Date qingmingFestival = holidayUtil.getHoliday(HolidayConstant.QINGMINGFESTIVAL, LocalDate.now().getYear());
LocalDate localDate = qingmingFestival.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(HolidayConstant.QINGMINGFESTIVAL +"时间为:" + localDate);
}
}
测试结果
清明节时间为:2022-04-05