Search code examples
javaandroidtimezoneutcdatetime-conversion

Convert timezone from CEST TIME to UTC in Android


I m building an application in Android studio using Api level 21.

I must convert a Date from CEST TIME | GMT | CET in UTC time.

This is the format time.

SimpleDateFormat utcFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
String dateToConvert = "2020-05-26T17:50:50.456";

This time is in CEST timezone format, I want to convert it in UTC time.


Solution

  • To "convert" a date to a specific time zone, specify the zone when formatting the Date value.

    In the following example, the time zone is explicitly specified for both the input format and the output format, so the example isn't dependent on the default time zone of the device running the code. You can of course leave the input time zone unspecified if you want to use the default time zone.

    TimeZone centralEurope = TimeZone.getTimeZone("Europe/Paris");
    TimeZone UTC = TimeZone.getTimeZone("UTC");
    
    SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    inputFormat.setTimeZone(centralEurope);
    
    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    outputFormat.setTimeZone(UTC);
    
    String dateToConvert = "2020-05-26T17:50:50.456";
    Date date = inputFormat.parse(dateToConvert);
    System.out.println(outputFormat.format(date));
    

    Output

    2020-05-26T15:50:50.456