计算两个字符串日期时间差是否小于24小时时遇DateTimeParseException错误
问题描述
尝试计算两个字符串格式的日期时间之差是否小于24小时,遇到以下错误:
java.time.format.DateTimeParseException: Text '20 4 01:40 AM' could not be parsed:
Unable to obtain LocalDateTime from TemporalAccessor: {DayOfMonth=20,
MonthOfYear=4},ISO resolved to 01:40 of type java.time.format.Parsed
使用的代码如下:
String today = "20 4 7:00 AM"; String tomorrow = "21 4 8:00 AM"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd M h:mm a"); LocalDateTime date1 = LocalDateTime.parse(today, formatter); LocalDateTime date2 = LocalDateTime.parse(tomorrow, formatter); long diffHours = Math.abs(Duration.between(date1, date2).toHours()); if (diffHours < 24) { System.out.println("The difference is less than 24 hours."); } else { System.out.println("The difference is greater than or equal to 24 hours."); }
错误原因
LocalDateTime需要年、月、日、时、分、秒的完整日期时间信息才能实例化,但你的日期字符串里没有年份,解析器无法生成合法的LocalDateTime对象,因此抛出异常。
解决方法
给解析器设置默认年份,同时指定支持AM/PM的英文Locale,确保解析正常:
String today = "20 4 7:00 AM"; String tomorrow = "21 4 8:00 AM"; // 构建带默认年份的格式化器 DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("dd M h:mm a") .parseDefaulting(ChronoField.YEAR, Year.now().getValue()) // 填充当前年份作为默认值 .toFormatter(Locale.US); // 指定英文Locale,保证AM/PM能被识别 LocalDateTime date1 = LocalDateTime.parse(today, formatter); LocalDateTime date2 = LocalDateTime.parse(tomorrow, formatter); long diffHours = Math.abs(Duration.between(date1, date2).toHours()); if (diffHours < 24) { System.out.println("时间差小于24小时。"); } else { System.out.println("时间差大于或等于24小时。"); }
注意事项
- 必须指定
Locale.US(或其他英文Locale),如果系统默认Locale非英文,解析器可能无法识别AM/PM标记,引发新的解析错误。 - 如果业务涉及跨年场景,需根据实际需求调整默认年份的设置,避免计算逻辑出错。
内容的提问来源于stack exchange,提问作者Tamara
相关产品推荐
相关产品推荐

