【问题标题】:convert local Date time to UTC format将本地日期时间转换为 UTC 格式
【发布时间】:2021-01-20 14:41:27
【问题描述】:

我想在 android 中将此 01/20/2021 20:10:14 转换为 yyyy-MM-dd'T'HH:mm:ss.SSS'Z' 格式。 目前我正在使用函数,但是当我转换为本地格式时,我没有得到原始时间

fun convertDate (date : String) : String {
        var convertedDate = ""
        val calendar = Calendar.getInstance()
        val timeformat = SimpleDateFormat("HH:mm:ss")
        val time = timeformat.format(calendar.time)
        val formatter = SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
        val odate = formatter.parse(date+" "+time)
        val utcformat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
        convertedDate = utcformat.format(odate)
        return convertedDate
    }

【问题讨论】:

  • 尝试在日历实例上设置时区

标签: android kotlin


【解决方案1】:

您应该对日期、时间等使用现代的java.time API。

首先我们需要格式化输入字符串。如问题评论中所述,正确格式化输入日期字符串需要区域信息。

这给了我们一个TemporalAccessor 对象。现在,我们需要将此对象转换为Instant 类的对象。 Instant 对象始终被视为 UTC。

fun convertDate (date : String) : String {
    val formatter = DateTimeFormatter
        .ofPattern("MM/dd/yyyy HH:mm:ss")
        .withZone(ZoneId.systemDefault())

    val instant = Instant.from(formatter.format(date))
    return instant.toString()
}

【讨论】:

  • 没错,但根据问题,格式化程序模式应该是“yyyy-MM-dd'T'HH:mm:ss.SSS'Z'”;)
  • 这里的模式是输入字符串的模式。输出字符串中的“Z”表示 UTC 时间。这是通过Instant 对象完成的
  • @KyzerSoze 我知道那个类,但是这个类从 API 级别 26 开始支持,我的 minsdk 是 21,所以我不能使用这个类
  • 如果可能的话,你可以使用desugaring
猜你喜欢
  • 2021-09-30
  • 2012-10-07
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 2015-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多