Search code examples
javaandroidutc

Convert UTC into Local Time on Android


In my project, I have get the API response in json format. I get a string value of time in UTC time format like this Jul 16, 2013 12:08:59 AM.
I need to change this into Local time. That is where ever we use this the app needs to show the local time. How to I do this?

Here is some Code I have tried:

String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getDefault());
String formattedDate = simpleDateFormat.format(aDate);

Assume aDate contains Jul 16, 2013 12:08:59 AM


Solution

  • Here's my attempt:

    String dateStr = "Jul 16, 2013 12:08:59 AM";
    SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a", Locale.ENGLISH);
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date date = df.parse(dateStr);
    df.setTimeZone(TimeZone.getDefault());
    String formattedDate = df.format(date);
    

    Also notice the "a" for the am/pm marker...