0

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
bircastri
  • 2,169
  • 13
  • 50
  • 119
  • 1
    How have you tried to do the conversion? – Andy Turner May 26 '20 at 16:12
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. May 26 '20 at 18:59

1 Answers1

1

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
Andreas
  • 154,647
  • 11
  • 152
  • 247