tl;博士
这会将示例String 转换为系统默认时区:
import java.time.ZonedDateTime
import java.time.ZoneId
fun main() {
// example String
val orderCreationDate = "2020-09-01T13:16:33.114Z"
// parse it to a ZonedDateTime and adjust the zone to the system default
val localZonedDateTime = ZonedDateTime.parse(orderCreationDate)
.withZoneSameInstant(ZoneId.systemDefault())
// print the adjusted values
println(localZonedDateTime)
}
输出取决于系统默认时区,在 Kotlin Playground 中,它产生以下行:
2020-09-01T13:16:33.114Z[UTC]
这显然意味着 Kotlin Playground 正在以 UTC 运行。
还有一点……
强烈建议现在使用java.time,并停止使用过时的库进行日期时间操作(java.util.Date、java.util.Calendar 以及java.text.SimpleDateFormat)。
如果您这样做,您可以在不指定输入格式的情况下解析此示例 String,因为它是按照 ISO 标准进行格式化的。
您可以创建一个偏移感知 (java.time.OffsetDateTime) 对象或区域感知对象
(java.time.ZonedDateTime),这取决于你。以下示例展示了如何解析您的 String、如何调整区域或偏移量以及如何以不同的格式打印:
import java.time.OffsetDateTime
import java.time.ZonedDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
fun main() {
// example String
val orderCreationDate = "2020-09-01T13:16:33.114Z"
// parse it to an OffsetDateTime (Z == UTC == +00:00 offset)
val offsetDateTime = OffsetDateTime.parse(orderCreationDate)
// or parse it to a ZonedDateTime
val zonedDateTime = ZonedDateTime.parse(orderCreationDate)
// print the default output format
println(offsetDateTime)
println(zonedDateTime)
// adjust both to a different offset or zone
val localZonedDateTime = zonedDateTime.withZoneSameInstant(ZoneId.of("Brazil/DeNoronha"))
val localOffsetDateTime = offsetDateTime.withOffsetSameInstant(ZoneOffset.ofHours(-2))
// print the adjusted values
println(localOffsetDateTime)
println(localZonedDateTime)
// and print your desired output format (which doesn't show a zone or offset)
println(localOffsetDateTime.format(
DateTimeFormatter.ofPattern("dd-MM-uuuu hh:mm a")
)
)
println(localZonedDateTime.format(
DateTimeFormatter.ofPattern("dd-MM-uuuu hh:mm a")
)
)
}
输出是
2020-09-01T13:16:33.114Z
2020-09-01T13:16:33.114Z
2020-09-01T11:16:33.114-02:00
2020-09-01T11:16:33.114-02:00[Brazil/DeNoronha]
01-09-2020 11:16 AM
01-09-2020 11:16 AM
要转换到系统区域或偏移量,请使用 ZoneId.systemDefault() 或 ZoneOffset.systemDefault() 而不是硬编码的。注意ZoneOffset,因为它不一定给出正确的,因为只有ZoneId 考虑夏令时。
如需更多信息,请参阅this question and its answer
有关为解析或格式化输出定义的格式的更多和更准确信息,您应该阅读the JavaDocs of DateTimeFormatter。