欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

如何在手机上将格林尼治零时区时间转换为当前当地时区 - Android (2023年11月1日 12点59分50秒)

最编程 2024-02-17 20:58:56
...

假设传入的是2023-11-01T12:59:10.420987这样的格式

要将格式为2023-11-01T12:59:10.420987的UTC时间字符串转换为Android设备本地时间,您可以使用java.time包中的类(在API 26及以上版本中可用)。如果您的应用需要支持较低版本的Android,您可以使用ThreeTenABP库,这是java.time包的一个后端移植。

以下是一个Kotlin示例,展示了如何进行转换:

import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
 
fun convertUtcToLocal(utcString: String): String {
    // 解析UTC时间字符串
    val utcDateTime = LocalDateTime.parse(utcString, DateTimeFormatter.ISO_DATE_TIME)
 
    // 将LocalDateTime转换为ZonedDateTime,使用UTC时区
    val zonedUtcDateTime = utcDateTime.atZone(ZoneOffset.UTC)
 
    // 获取设备当前的时区
    val currentZoneId = ZoneId.systemDefault()
 
    // 转换为本地时区的时间
    val localDateTime = zonedUtcDateTime.withZoneSameInstant(currentZoneId)
 
    // 格式化输出(如果需要)
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    return localDateTime.format(formatter)
}
 
// 示例使用
fun main() {
    val utcString = "2023-11-01T12:59:10.420987"
    val localDate = convertUtcToLocal(utcString)
    println("Local Date: $localDate")
}

在这个例子中,java.time.LocalDateTime.parse()用于解析UTC时间字符串,然后使用atZone(ZoneOffset.UTC)将其转换为ZonedDateTime。之后,使用withZoneSameInstant(currentZoneId)将UTC时间转换为本地时区时间。

请注意,java.time包在Android API 26以上版本中可用。如果您的应用目标是较低版本的Android,您可能需要使用ThreeTenABP库来获得类似的功能。