jean d'arme jean d'arme - 2 months ago 8
Java Question

Date TimeZone conversion

I have done conversion method from UTC String to date in local timezone, but it just returns the same date as in the String. What is wrong here?

public static Date getUTCToDate(String utc){
// String exampleOfUTCTime = "2016-09-27T19:35:32.717";

try{
Log.d("asd-timeBefore", "getUTCToDate: " + utc);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getDefault());
Date d = formatter.parse(utc);
Log.d("asd-timeAfter", "getUTCToDate: " + d);
return d;
} catch (ParseException e){
e.printStackTrace();
}
return null;
}

Answer

Try to change your code, like this. It will convert UTC time zone to local time zone :

public static Date getUTCToDate(String utc){
    // String exampleOfUTCTime = "2016-09-27T19:35:32.717";

    try{
        Log.d("asd-timeBefore", "getUTCToDate: " + utc);
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date d = formatter.parse(utc);
        Log.d("asd-timeAfter", "getUTCToDate: " + d);
        return d;
    } catch (ParseException e){
        e.printStackTrace();
    }
    return null;
}