我一直在尝试将当地时间(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日的日光节约时间之前有效。您知道我在做什么错吗?
我一直在尝试将当地时间(EST)转换为UTC,反之亦然。因此,我展示了一个时间选择器,用户选择了时间,然后将其转换为UTC并发送到服务器。这是代码:val ...
请不要在日期和时间上使用过时且设计不良的Java api。使用新的java.time API。它更健壮,更易于使用。
我最终得到以下解决方案。我知道服务器中字符串的格式,因此我将其拆分。我不想使用新的时间API,因为它可以从API级别26开始使用。