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

如何用DateTimeFormatter将Java LocalDateTime格式化为指定JSON日期格式

问题:将Java LocalDateTime格式化为指定JSON日期格式

我需要把Java的java.time.LocalDateTime格式化为符合2023-09-17T00:00:00.000+00:00格式的JSON字符串。我尝试使用DateTimeFormatter.ISO_DATE_TIME,代码如下:

date.plusDays(daysToAdd)
   .atZone(ZoneOffset.UTC)
   .format(DateTimeFormatter.ISO_DATE_TIME)

但得到的结果是2023-09-17T00:00:00Z。请问是否有符合该格式的预定义格式化器?若需要自定义DateTimeFormatter,请提供示例。


编辑

我最终参考相关示例及评论,使用了如下格式化器:

val jsonDateTimeFormatter: DateTimeFormatter = new DateTimeFormatterBuilder()
    .append(DateTimeFormatter.ISO_LOCAL_DATE)
    .appendLiteral('T')
    .appendPattern("HH:mm:ss.SSS")
    .appendOffset("+HH:MM", "+00:00")
    .toFormatter()

解答

Java标准库中没有直接匹配2023-09-17T00:00:00.000+00:00格式的预定义DateTimeFormatter。ISO_DATE_TIME在处理UTC时区时会输出Z后缀,而非+00:00,同时默认不会强制保留三位毫秒数(若时间毫秒部分为0,可能会省略)。

要实现目标格式,需自定义DateTimeFormatter,核心要满足两个要求:

  • 强制输出三位毫秒数
  • 将UTC时区显示为+00:00而非Z

以下是Java版本的自定义格式化器示例:

DateTimeFormatter customFormatter = new DateTimeFormatterBuilder()
        .append(DateTimeFormatter.ISO_LOCAL_DATE)
        .appendLiteral('T')
        .appendPattern("HH:mm:ss.SSS") // 固定三位毫秒格式
        .appendOffset("+HH:mm", "+00:00") // 指定偏移格式,UTC时显示+00:00
        .toFormatter();

// 使用示例
LocalDateTime localDateTime = LocalDateTime.now();
String formatted = localDateTime.atZone(ZoneOffset.UTC).format(customFormatter);
System.out.println(formatted); // 输出示例:2023-09-17T00:00:00.000+00:00

你最终使用的Scala版本格式化器已经完全满足需求:appendPattern("HH:mm:ss.SSS")确保毫秒部分为三位,appendOffset("+HH:MM", "+00:00")指定了UTC偏移的显示格式,完美匹配目标JSON日期格式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 16:13:17