介绍
基于HuTool工具类时间工具类,获取今年的所有法定节假日
获取今年所有的周末
public static Map<DateTime,String> getAllWeekend(){
return new HashMap<DateTime,String>(){{
for (DateTime dateTime : getAllDayOfYear()) {//今年的所有日期
if (DateUtil.isWeekend(dateTime)){
put(dateTime, dateTime.dayOfWeekEnum().toChinese());
}
}
}};
}
获取今年所有的法定假日
默认今年:https://timor.tech/api/holiday/year/
指定年:https://timor.tech/api/holiday/year/2023
指定年和月:https://timor.tech/api/holiday/year/2023-10
private static final String HOLIDAY_URL = "https://timor.tech/api/holiday/year/";
public static Map<DateTime,String> getAllHoliday(Integer year){
String url = year != null ? HOLIDAY_URL+year : HOLIDAY_URL;
String response = HttpUtil.get(url);
Collection<Object> holidays = JSONUtil.parseObj(response).getJSONObject("holiday").values();
return new HashMap<DateTime,String>(32){{
for (Object holiday : holidays) {
JSONObject dateJson = JSONUtil.parseObj(holiday);
String name = dateJson.getStr("name");
if (!name.contains("补")){//排除补班
put(DateTime.of(dateJson.getDate("date")),name);
}
}
}};
}
整体代码
public class HolidayUtil {
private static final String HOLIDAY_URL = "https://timor.tech/api/holiday/year/";
/**
* 获取今年的所有法定节假日包括周末
*/
public static Map<DateTime,String> getAllDayOff(){
//周末
Map<DateTime, String> allWeekend = getAllWeekend();
//法定假日
allWeekend.putAll(getAllHoliday(null));
//排序并返回结果
return allWeekend.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue,
LinkedHashMap::new)
);
}
/**
* 获取今年的所有周末
*/
public static Map<DateTime,String> getAllWeekend(){
return new HashMap<DateTime,String>(){{
for (DateTime dateTime : getAllDayOfYear()) {//今年的所有日期
if (DateUtil.isWeekend(dateTime)){
put(dateTime, dateTime.dayOfWeekEnum().toChinese());
}
}
}};
}
/**
* 获取到今年的所有节日
* key date 日期
* value info 描述
*{
* "holiday":true,
* "name":"元旦",
* "wage":3,
* "date":"2023-01-01",
* "rest":1
*}
*/
public static Map<DateTime,String> getAllHoliday(Integer year){
String url = year != null ? HOLIDAY_URL+year : HOLIDAY_URL;
String response = HttpUtil.get(url);
Collection<Object> holidays = JSONUtil.parseObj(response).getJSONObject("holiday").values();
return new HashMap<DateTime,String>(32){{
for (Object holiday : holidays) {
JSONObject dateJson = JSONUtil.parseObj(holiday);
String name = dateJson.getStr("name");
if (!name.contains("补")){//排除补班
put(DateTime.of(dateJson.getDate("date")),name);
}
}
}};
}
/**
* 获取今年的所有天
*/
public static List<DateTime> getAllDayOfYear(){
DateTime now = DateTime.now();
DateTime begin = DateUtil.beginOfYear(now);//今年的开始
DateTime end = DateUtil.endOfYear(now);//今年的结束
return DateUtil.rangeToList(begin,end, DateField.DAY_OF_YEAR);//今年的所有日期
}
}