Display time without converting to local time zone

Viewed 143

I have an API that gives me this JSON response

{
  "time": "2020-05-25T05:18:02.279842+01:00",
  "timezone_name": "LMT",
  "timezone": "Europe/London"
}

Now, I have 2 problems.

  1. Converting the time to date object. I used SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ") but, gives me parse exception. I think it’s because of milliseconds which is in 6 digits SSSSSS(279842). So I converted this 2020-05-25T05:18:02.279842+01:00" to 2020-05-25T05:18:02.279+01:00" which worked. I’m not satisfied with string manipulation.

  2. When I format the date from above, I see the time in my local time zone not the London time. I think I have to set the time zone for the date object which is given in the time zone.

Overall, I just want to neatly parse the txt to data object and show the time in given time zone.

Appreciate your inputs.

2 Answers

I ended up with this solution.

private fun format(str: String): String {
        // expected input format "2020-05-24T08:19:40.807726-05:00"
        try {
            val slits = str.split(".")
            val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
            inputFormat.timeZone = TimeZone.getTimeZone(timezone/*"Europe/London"*/)

            val outputFormat = SimpleDateFormat("h:mm a")
            outputFormat.timeZone = inputFormat.timeZone
            return outputFormat.format(inputFormat.parse(slits[0])!!)
        } catch (e: Exception) {
            Log.e(MWLocationInfo::class.java.simpleName, e.stackTrace.toString());
        }
        return "-"
    }

About 2 - SimpleDateFormat always returns time in local time of JVM, so you need to set timezone to SimpleDateFormat as

TimeZone timeZone = TimeZone.getTimeZone("Europe/London");
simpleDateFormat.setTimeZone(timeZone);

SimpleDateFormat is now legacy, think of using java.time API (introduced in java 8). Using java.time API -

ZonedDateTime zonedDateTime = ZonedDateTime.parse("2020-05-25T05:18:02.279842+01:00[Europe/London]");
Related