Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display time without converting to local time zone

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.

like image 476
Sundeep1501 Avatar asked Dec 01 '25 10:12

Sundeep1501


1 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 "-"
    }

like image 93
Sundeep1501 Avatar answered Dec 04 '25 00:12

Sundeep1501



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!