Reputation: 1677
I am getting below date from in UTC format from the server :
2021-05-20 09:14:55
Now, I have to convert it into local with 24 hours format and 12 hours format as well.
To convert it into 24 hours format I have done as below :
val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
df.timeZone = TimeZone.getTimeZone("UTC")
val date = df.parse(dataDate)
df.timeZone = TimeZone.getDefault()
val formattedDate = df.format(date)
and got the result as : 2021-05-20 14:44:55 (24 hour local)
Now, I have tried to convert same date to local with 12 hour format as below :
val utc = TimeZone.getTimeZone("UTC")
val inputFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.ENGLISH)
inputFormat.timeZone = utc
val outputFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss aa",
Locale.ENGLISH)
outputFormat.timeZone = utc
val dateInput = inputFormat.parse(dataDate)
val output = outputFormat.format(dateInput)
It give me output as 2021-05-20 09:14:55 AM (12 hour local)
I think this is wrong its just adding AM as suffix. This might be wrong because If 24 hour date result is 2021-05-20 14:44:55 then 12 hour date result should be 2021-05-20 02:44:55 PM
What might be the issue?
Upvotes: 1
Views: 3506
Reputation: 15552
You are using TimeZone.getDefault()
to print the 24H format, and TimeZone.getTimeZone("UTC")
to print the 12H format.
df.timeZone = TimeZone.getDefault()
val formattedDate = df.format(date)
outputFormat.timeZone = utc
val output = outputFormat.format(dateInput)
TimeZone.getDefault()
uses your local time zone, which is not UTC in this case.
Use local timezone for 12H format just like 24H format.
outputFormat.timeZone = TimeZone.getDefault()
Upvotes: 1