【发布时间】:2020-06-22 17:29:26
【问题描述】:
我一直在尝试将本地时间 (EST) 转换为 UTC,反之亦然。因此,我提出了一个时间选择器,用户选择时间,我将其转换为 UTC 并发送到服务器。代码如下:
val cal = Calendar.getInstance()
cal.set(Calendar.HOUR_OF_DAY, mHour) //mHour = 15
cal.set(Calendar.MINUTE, mMinute) //mMinute = 00
cal.set(Calendar.SECOND, 0)
val formatter = SimpleDateFormat("HH:mm:ss")
formatter.timeZone = TimeZone.getTimeZone("UTC")
val cutOffTime = formatter.format(cal.time) //this gives 19:00:00 which is correct
上面的 cutOffTime 输出是正确的,因为 15:00 EST 在考虑夏令时后是 19:00 UTC。
现在,我从服务器获取相同的 cutOffTime,将其转换为本地 (EST) 并显示。代码如下:
val cutOffTime = jsonObject.get("cutOffTime").getAsString()) //value is 19:00:00
var cutoffTime: Time? = null
val format = SimpleDateFormat("hh:mm:ss")
format.timeZone = TimeZone.getTimeZone("UTC")
cutoffTime = Time(format.parse(cutOffTime).time)
//cutoffTime has value 14:00 which is strange, it should be 15:00
所以,上面代码中的 cutoffTime 的值是 14:00,这很奇怪,应该是 15:00。 请注意,此代码在 2020 年 3 月 8 日夏令时之前有效。知道我做错了什么吗?
【问题讨论】: