• 0时区格林威治时间转换手机当地时间-Android


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

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

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

    1. import java.time.LocalDateTime
    2. import java.time.ZoneId
    3. import java.time.ZoneOffset
    4. import java.time.ZonedDateTime
    5. import java.time.format.DateTimeFormatter
    6. fun convertUtcToLocal(utcString: String): String {
    7. // 解析UTC时间字符串
    8. val utcDateTime = LocalDateTime.parse(utcString, DateTimeFormatter.ISO_DATE_TIME)
    9. // 将LocalDateTime转换为ZonedDateTime,使用UTC时区
    10. val zonedUtcDateTime = utcDateTime.atZone(ZoneOffset.UTC)
    11. // 获取设备当前的时区
    12. val currentZoneId = ZoneId.systemDefault()
    13. // 转换为本地时区的时间
    14. val localDateTime = zonedUtcDateTime.withZoneSameInstant(currentZoneId)
    15. // 格式化输出(如果需要)
    16. val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    17. return localDateTime.format(formatter)
    18. }
    19. // 示例使用
    20. fun main() {
    21. val utcString = "2023-11-01T12:59:10.420987"
    22. val localDate = convertUtcToLocal(utcString)
    23. println("Local Date: $localDate")
    24. }

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

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

  • 相关阅读:
    DQL、DML、DDL、DCL的概念与区别
    Fabric.js 自定义选框样式
    kibana 7安装
    弱网测试探索
    MYSQL 关键字相似度排序
    【SpringBoot系列教程-目录大纲】
    查分小程序,教学大作用
    基于java+springboot的人事招聘信息网站
    Vue 项目中用户登录及 token 验证的思路
    541、RabbitMQ详细入门教程系列 -【Jackson2JsonMessageConvert】 2022.09.05
  • 原文地址:https://blog.csdn.net/loveseal518/article/details/134530022