如何使用kotlin将时间从服务器转换为本地区域



我从服务器得到一个时间,我想将其更改为本地区域如何使用Kotlin
来自服务器的时间就像";2020-09-01T3:16:31.14Z">
这是我的代码:


val dateStr = order.creationDate
val df = SimpleDateFormat("dd-MM-yyyy HH:mm aa", Locale.getDefault())
df.timeZone = TimeZone.getDefault()
val date = df.parse(dateStr)
val formattedDate = df.format(date)
textViewDateOrderDetail.text = formattedDate

order.createDate:来自服务器的时间

tl;dr

这将把示例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游乐场,它产生以下行:

2020-09-01T13:16:33.114Z[UTC]

这显然意味着科特林游乐场在UTC比赛。


更多。。。

强烈建议现在使用java.time,并停止使用过时的库进行日期时间操作(java.util.Datejava.util.Calendarjava.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考虑夏令时。有关更多信息,请参阅此问题及其答案

有关要定义用于解析或格式化输出的格式的更多、更准确的信息,您应该阅读DateTimeFormatter的JavaDocs。