我一直在尝试将当地时间(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。
现在,我从服务器获取相同的cutTime,并将其转换为本地(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日的日光节约时间之前有效。知道我在做什么错吗?