java - 将 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 格式?
解决方案
我喜欢这个格式化程序:
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);
它给出与以前相同的结果。
推荐阅读
- r - 将信息从行转换为新列
- python - 用张量 B 的每一行减去张量 A 的每一行
- hyperledger-fabric - 无法在超级账本结构网络上实例化链码
- python - 如何将正则表达式用于从 1 到 100 的罗马数字?
- mysql - celery worker 闲置 24 小时时数据库连接错误
- php - 如何检查 Codeigniter 中是否只有特定的表列受到影响?
- node.js - 需要正则表达式来搜索包含“+”的字符串
- python - 自定义字段验证错误不显示字段名称
- laravel - Larvel 5.8:如何在不附加整个关系的情况下使用静态 $appends?
- reactjs - 未处理的拒绝(TypeError):无法读取未定义的属性“catch”