I have been trying to convert local time (EST) to UTC and vice versa. So, I present a time picker, user selects the time, I convert the same to UTC and send to server. Here's the code:
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
Above output for cutOffTime is correct as 15:00 EST is 19:00 UTC after considering day light savings.
Now, I fetch this same cutOffTime from server, convert it to local (EST) and display. Here's the code:
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
So, cutoffTime in above code has value 14:00 which is strange, it should be 15:00. Please note that this code was working before day light savings on March 8, 2020. Any idea what am I doing wrong?
Please don't use the old and badly designed java api for date and times. Use the new java.time api. It's much more robust and is nicer to use.
Here is an example on how to do your code with java.time:
The great benefit is that the api will handle everything regarding summertime and wintertime for you. Have read here for information about the
ESTand why you shouldn't use it.The problem you face is probably due to the fact that you used
HHin one formatter buthhin the other one. Those are not the same. Have read here about Patterns for Formatting and Parsing.