Java将ISO8601时间戳转换为指定日期格式时出现空指针异常
问题根因
- 格式匹配错误:待解析的时间字符串为
2021-04-05T16:25:45.000+00:00,但定义的输入解析格式串yyyy-MM-dd'T'HH:mm:ss.SSS'Z'将Z作为字面常量匹配,实际字符串末尾是+00:00时区偏移,解析过程直接抛出ParseException,parsedDate始终保持初始的null值。 - 缺少异常分支拦截:解析抛错后代码没有中断流程,直接将null对象传入
outputFormat.format()方法,最终触发空指针异常。
解决方案
方案1:修正原有SimpleDateFormat的逻辑
调整解析格式串匹配规则,补全空值/异常拦截逻辑,同时修正时区计算偏差:
String date = "2021-04-05T16:25:45.000+00:00"; // 格式串中XXX用于匹配ISO 8601标准的时区偏移(如+00:00),不要再把Z作为字面量匹配 SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); // 必须将输入解析器的时区设为UTC,避免按本地时区错算时间值 inputFormat.setTimeZone(TimeZone.getTimeZone("UTC")); SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a"); Date parsedDate = null; try { parsedDate = inputFormat.parse(date); } catch (ParseException e) { e.printStackTrace(); // 解析失败直接走错误分支,不要继续向下执行 throw new RuntimeException("时间格式解析失败", e); } String formattedDate = outputFormat.format(parsedDate);
注意:输出格式中
a对应的上下午标识,会根据格式化实例绑定的Locale自动切换展示语言,如需固定为英文AM/PM展示,可在初始化输出格式化器时传入指定Locale:SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.ENGLISH);
方案2:使用Java 8+ 原生java.time API(推荐)
SimpleDateFormat存在线程安全隐患,处理ISO格式时间时极易出现格式串匹配错误,新的时间API原生支持标准格式解析,无需自定义复杂格式串,稳定性更高:
String date = "2021-04-05T16:25:45.000+00:00"; // 直接解析为带时区偏移的时间对象,无需自定义解析规则 OffsetDateTime utcTime = OffsetDateTime.parse(date); // 按需求定义输出格式 DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a"); // 若需转成本地时区展示,可追加时区转换逻辑: // String formattedDate = utcTime.atZone(ZoneId.systemDefault()).format(outputFormatter); String formattedDate = utcTime.format(outputFormatter);
内容的提问来源于stack exchange,提问作者user12359279
相关产品推荐
相关产品推荐

