将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并向他们发送我的即时对象的字符串版本(通过调用即时对象上的.toString()方法)。

然而,我注意到外部API接受的格式和我发送的格式有点不同。这是外部API接受的:2021-10-10T12:34:56.000Z这是我发送的:2021-10-10T11:34:56Z。如你所见,我漏掉了日期后面的000。

是否有任何格式化即时对象以符合外部API格式的方法?

我喜欢这个格式器:

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 - 10 t19: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);

给出与之前相同的结果。

最新更新