You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中转换带时区日期字符串为dd-MM-yyyy格式的正确方法

正确解析带时区偏移的日期并转换格式

问题原因

解析失败是因为输入日期的时区偏移格式(-05:00)和你指定的格式模式不匹配:

  • 原日期的时区部分是带冒号的小时偏移(如-05:00),对应DateTimeFormatter的模式符号是XXX
  • 你之前尝试的模式要么错误添加了毫秒部分(SSS,但原日期没有毫秒),要么时区符号不对,导致解析到索引19(时区起始位置)时失败

正确实现代码

用匹配的格式解析后再转换即可,代码如下:

// 输入格式匹配带时区偏移的ISO格式(不带毫秒)
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ENGLISH);
// 输出格式注意是yyyy(你之前写的yyy少了一个y)
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy", Locale.ENGLISH);

// 先解析为带偏移的日期时间,再转成LocalDate
OffsetDateTime offsetDateTime = OffsetDateTime.parse(localBill.getBillCycleDate(), inputFormatter);
LocalDate date = offsetDateTime.toLocalDate();

String formattedDate = outputFormatter.format(date);

更简便的方式

你的输入是标准ISO 8601格式(带时区偏移),OffsetDateTime可以直接无需自定义格式完成解析,代码更简洁:

DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy", Locale.ENGLISH);

// 直接解析ISO格式字符串
OffsetDateTime offsetDateTime = OffsetDateTime.parse(localBill.getBillCycleDate());
LocalDate date = offsetDateTime.toLocalDate();

String formattedDate = outputFormatter.format(date);

注意事项

  • 输出格式必须写yyyy而非yyy,否则年份会缺失一位(比如2022会变成022)
  • 若业务只关心日期本身、不涉及跨时区转换,上述方法完全适用

内容的提问来源于stack exchange,提问作者Abd Maj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:03:39