Java中将字符串类型日期转换为LocalDateTime格式报错如何解决?
报错原因
你定义的DateTimeFormatter模式串中,T属于固定文本,没有用单引号包裹,DateTimeFormatter会将其识别为日期时间模式字符,但Java日期模式中不存在T对应的规则,因此抛出Unknown pattern letter T错误。同时你的转换逻辑存在两个隐含问题:
LocalDateTime本身不携带时区/偏移信息,无法直接输出你需要的-05:00后缀- 原有
set方法的catch分支使用ISO_DATE_TIME解析仅含日期的字符串,会直接抛出解析异常,因为该格式要求字符串必须携带时间部分
解决步骤
1. 修正String类型参数的set方法
兼容时间戳、纯日期、带时间的日期三种输入格式:
public void setRelationshipStatusDate(String time) { if (time != null) { // 固定使用你需要的-05:00时区偏移 ZoneOffset targetOffset = ZoneOffset.ofHours(-5); try { long epochTime = Long.parseLong(time); this.relationshipStatusDate = LocalDateTime.ofInstant(Instant.ofEpochMilli(epochTime), targetOffset); } catch (NumberFormatException e){ try { // 优先解析纯日期格式(yyyy-MM-dd),自动补全0点 LocalDate localDate = LocalDate.parse(time, DateTimeFormatter.ISO_LOCAL_DATE); this.relationshipStatusDate = localDate.atStartOfDay().toLocalDateTime(); } catch (DateTimeParseException ex) { // 兼容带时间的标准日期格式 this.relationshipStatusDate = LocalDateTime.parse(time, DateTimeFormatter.ISO_DATE_TIME); } } } }
2. 输出指定格式的带偏移字符串
需要把LocalDateTime绑定目标偏移后再格式化,不要写死固定的时分秒和偏移量到模式串中:
// 定义输出格式,固定文本T用单引号包裹,XXX对应时区偏移输出 DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); ZoneOffset targetOffset = ZoneOffset.ofHours(-5); // 给LocalDateTime绑定偏移后格式化 OffsetDateTime offsetDateTime = relationshipStatusDate.atOffset(targetOffset); String result = offsetDateTime.format(outputFormatter);
输入"2021-07-25"时,输出结果为2021-07-25T00:00:00.000-05:00,完全符合预期。
内容的提问来源于stack exchange,提问作者challengeAccepted
相关产品推荐
相关产品推荐

