Java时间日期类处理(LocalDateTime、LocalDate相关操作、获取周几、工作日休息日节假日判定)
1.LocalDateTime相关操作:(时间推移、计算两个LocalDateTime之间的时间间隔、转LocalDate),代码如下:
// 获取LocalDateTime对象
String dateTime1 = "2022-08-20 00:00:00";
String dateTime2 = "2022-08-20 23:00:00";
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime ldt1 = LocalDateTime.parse(dateTime1, df);
LocalDateTime ldt2 = LocalDateTime.parse(dateTime2, df);
// ldt1往前推31天,即在原来的基础上-31天
LocalDateTime localDateTime = ldt1.minusDays(31);
// 输出结果:2022-07-20 00:00:00
System.out.println(localDateTime.format(df));
// 计算两个LocalDateTime的时间间隔(时分秒),ldt1是开始时间,ldt2是结束时间
Duration between = Duration.between(ldt1, ldt2);
// 如:ldt1与ldt2间隔多少小时
long hours = between.toHours();
// 输出结果23
System.out.println(hours);
// LocalDateTime转LocalDate对象
LocalDate date = ldt1.toLocalDate();
2.LocalDate相关操作(获得月份天数、获取月初月末、获取周一),沿用上方代码的date对象完成操作,代码如下:
// 获取月份天数
int lengthOfMonth = date.lengthOfMonth();
// 输出结果:31,即2022年8月共31天
System.out.println(lengthOfMonth);
// 获取月初
LocalDate month = date.with(TemporalAdjusters.firstDayOfMonth());
// 获取月末
LocalDate month = date.with(TemporalAdjusters.lastDayOfMonth());
// 获取周一
LocalDate week = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
3.获取周几,代码如下:
/**
* 获取周几
*
* @param datetime 日期,格式为:20220801
* @return 周几
* @throws java.text.ParseException 异常
*/
private static String dateToWeek(String datetime) throws java.text.ParseException {
SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
Calendar cal = Calendar.getInstance(); // 获得一个日历
Date date = null;
date = (Date) f.parse(datetime);
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}
main方法运行:
public static void main(String[] args) throws ParseException {
// 获取周几:结果:星期四
System.out.println(dateToWeek("20220915"));
}
4.判断工作日、休息日、节假日方法(代码作者参考文档:API介绍 · 免费节假日API · 看云),注意,代码作者说明查一次要间隔500毫秒(个人建议最好间隔1秒)以防被拉近黑名单,可以批量查询,以下主要讲批量获取某月的工作日、休息日、节假日代码实现。
工具类:
/**
* 调用API接口判断日期是否是工作日 周末还是节假日,工作日对应结果为 0, 休息日对应结果为 1, 节假日对应的结果为 2
*
* @author djh
* @since 2022-08-26
*/
public class HolidayUtil {
/**
* 请求接口
*
* @param httpArg :参数:yyyyMMdd,如20220826,可支持多个,如:20220801,20220802,……
* @return 返回结果:工作日对应结果为 0, 休息日对应结果为 1, 节假日对应的结果为 2
*/
public static String request(String httpArg) {
String httpUrl = "http://tool.bitefu.net/jiari/";
BufferedReader reader = null;
String result = null;
StringBuilder stringBuffer = new StringBuilder();
httpUrl = httpUrl + "?d=" + httpArg;
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
stringBuffer.append(strRead);
}
reader.close();
result = stringBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
业务代码:
/**
* 获取指定年月的工作日、休息日、节假日信息
*
* @param time 时间
*/
public void save(LocalDate time) {
// 获取月的天数
int totalDays = time.lengthOfMonth();
// 获取年月字符串
String yearAndMonth = time.getYear() + "" + time.getMonthValue();
if (time.getMonthValue() < 10) {
// 补0,如8补为08
yearAndMonth = time.getYear() + "0" + time.getMonthValue();
}
StringBuilder date = new StringBuilder();
// 拼接参数
for (int i = 1; i <= totalDays; i++) {
date.append(yearAndMonth);
if (i < 10) {
date.append("0").append(i).append(",");
} else {
date.append(i).append(",");
}
}
// 查询结果是一个json对象,如:{"20220901: "0","20220902: "0",……}
// 需要将查询结果封装为List<Map>进行json解析, 解析出的List<Map>集合里只有一个map元素,这个map的key为日期如20220901,value为工作日、休息日、节假日的判定
String request = HolidayUtil.request(date.toString());
request = "[" + request + "]";
List<Map> list = JSON.parseArray(request, Map.class);
for (Map map : list) {
// set集合中就是该月日期集合,如20220901,之后根据业务需要进行操作即可
Set set = map.keySet();
for (Object o : set) {
String dateStr = (String) o;
}
}
}
版权声明:本文为weixin_64841689原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。