Abo Hani Abo Hani - 1 year ago 47
Java Question

GMT To Local Covert In Wrong Way ( False Value )

i have the following code that converts GMT time to local time, I took it from an answer here on StackOverflow, the problem is that this code return a false value of GMT time .

My GMT Time is : +3, but the code is using +2, it takes the GMT time from my device i guess, and my device's time is +3 GMT .

Here's the code :

String inputText = "12:00";
SimpleDateFormat inputFormat = new SimpleDateFormat
("kk:mm", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat outputFormat =
new SimpleDateFormat("kk:mm");
// Adjust locale and zone appropriately
Date date = null;
try {
date = inputFormat.parse(inputText);
} catch (ParseException e) {
e.printStackTrace();
}
String outputText = outputFormat.format(date);
Log.i("Time","Time Is: " + outputText);


The log returns : 14:00

Answer Source

This is related to the date on which you are doing the conversion.

You are only specifying the hours and minutes, so the calculation is being done on January 1 1970. On that date, presumably, the GMT offset in your timezone is just 2 hours.

Specify the date too.


SimpleDateFormat inputFormat =
    new SimpleDateFormat("kk:mm", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat outputFormat =
    new SimpleDateFormat("yyyy/MM/dd kk:mm", Locale.US);
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

Date date = inputFormat.parse("12:00");

System.out.println("Time Is: " + outputFormat.format(date));

Ideone demo

Output:

Time Is: 1970/01/01 12:00

Additional code to show Daylight Savings Time / Summer Time impact:

SimpleDateFormat gmtFormat = new SimpleDateFormat("yyyy/MM/dd kk:mm", Locale.US);
gmtFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat finlandFormat = new SimpleDateFormat("yyyy/MM/dd kk:mm zzz", Locale.US);
finlandFormat.setTimeZone(TimeZone.getTimeZone("Europe/Helsinki"));

SimpleDateFormat plus3Format = new SimpleDateFormat("yyyy/MM/dd kk:mm zzz", Locale.US);
plus3Format.setTimeZone(TimeZone.getTimeZone("GMT+3"));

Date date = gmtFormat.parse("1970/01/01 12:00");
System.out.println("Time Is: " + gmtFormat.format(date));
System.out.println("Time Is: " + finlandFormat.format(date));
System.out.println("Time Is: " + plus3Format.format(date));

date = gmtFormat.parse("2016/04/22 12:00");
System.out.println("Time Is: " + gmtFormat.format(date));
System.out.println("Time Is: " + finlandFormat.format(date));
System.out.println("Time Is: " + plus3Format.format(date));

Output:

Time Is: 1970/01/01 12:00
Time Is: 1970/01/01 14:00 EET         <-- Eastern European Time
Time Is: 1970/01/01 15:00 GMT+03:00
Time Is: 2016/04/22 12:00
Time Is: 2016/04/22 15:00 EEST        <-- Eastern European Summer Time
Time Is: 2016/04/22 15:00 GMT+03:00