首页 > 解决方案 > Scala - 如何将 LocalDateTime 转换为无 GMT 后缀格式的 ZonedDateTime?

问题描述

我想在 GMT 中获取 LocalDateTime,所以用 ZonedDateTime 包装它。

但是gmtZoneTime以以下格式返回:2019-10-29T00:00Z[GMT]虽然我需要它:2019-10-29T00:00:00.000+0000

我应该如何正确转换localDateTime为 GMT ZonedDateTime?

val currentDate:LocalDate = java.time.LocalDate.now
val localDateTime: LocalDateTime = currentDate.atStartOfDay
val gmtZoneTime: ZonedDateTime = localDateTime.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("GMT"))

标签: javascaladatetimetime

解决方案


您需要将ZonedDateTime.

第一种方法是使用预定义的格式化程序,例如:java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME,但是因为GMT它显示“Z”而不是“+0000”(默认行为,其他偏移量显示为“+0100”等)

所以第二个是创建自己的格式化程序,例如: java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")

然后用它来格式化ZonedDateTime,这样gmtZoneTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")) 你就会得到如下结果:

2019-10-28T23:00:00+0000

推荐阅读