首页 > 解决方案 > 将 DateTime 转换为特定格式

问题描述

我有一个端点,其中将以下 json 作为其请求正文:

{"timestamp":"2021-10-10 21:46:07"}

我通过执行以下操作将此时间戳字符串转换为 Instant:

   private Instant formatTimestamp(String timestamp)
   {
      final DateTimeFormatter formatter = DateTimeFormatter
                                             .ofPattern("yyyy-MM-dd HH:mm:ss")
                                             .withZone(ZoneId.systemDefault());

      return Instant.from(formatter.parse(timestamp));

   }

然后我调用一个外部 API 并向他们发送我的 Instant 对象的字符串版本(通过调用.toString()Instant 对象上的方法)。

但是我注意到外部 API 接受的格式和我发送的格式有点不同。这是外部 API 接受的: 2021-10-10T12:34:56.000Z 这是我发送的:2021-10-10T11:34:56Z。如您所见,我错过了日期的尾随 000。

有没有办法格式化即时对象以符合外部 API 格式?

标签: javajsondatetime

解决方案


我喜欢这个格式化程序:

private static final DateTimeFormatter INSTANT_FORMATTER = new DateTimeFormatterBuilder()
        .append(DateTimeFormatter.ISO_LOCAL_DATE)
        .appendLiteral('T')
        .appendPattern("HH:mm:ss.SSSX")
        .toFormatter(Locale.ROOT)
        .withZone(ZoneOffset.UTC);

示范:

    Instant parsedInstant = formatTimestamp("2021-10-10 21:46:07");
    String formattedTimestamp = INSTANT_FORMATTER.format(parsedInstant);
    System.out.println(formattedTimestamp);

我的时区的输出是:

2021-10-10T19:46:07.000Z

.SSS我使用的格式模式字符串中,精确指定了秒的三位小数。我还指定格式化程序必须始终使用 UTC ( ZoneOffset.UTC),因为您的服务需要 UTC 的尾随Z。我的格式化程序可能有点罗嗦,因为我想重用内置的DateTimeFormatter.ISO_LOCAL_DATE. 如果你喜欢它更短:

private static final DateTimeFormatter INSTANT_FORMATTER
        = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSX", Locale.ROOT)
                .withZone(ZoneOffset.UTC);

它给出与以前相同的结果。


推荐阅读