master94ga master94ga - 2 months ago 20
Android Question

Convert UTC date to current timezone

I have to convert a UTC date in this format "2016-09-25 17:26:12" to the current time zone of Android. I did this:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(temp.getString("date"));
System.out.println(mydate.toString());


This works but I don't know why it print also "GMT+02:00".
This is the Output: "Sun Sep 25 19:26:12 GMT+02:00 2016", I don't want to show "GMT+02:00".

EDIT, CODE OF THE SOLUTION:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat outputSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date myDate = simpleDateFormat.parse(temp.getString("date"));
System.out.println(outputSdf.format(myDate));

Answer

it print GMT+02 because this is your "local" timezone. if you want to print the date without timezone information, use SimpleDateFormat to format the date to you liking.

edit : adding the code example (with your variable 'myDate')

SimpleDateFormat inputSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
inputSDF.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = inputSDF.parse("2016-09-25 17:26:12");
//
SimpleDateFormat outputSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(outputSDF.format(myDate));
System.out.println(TimeZone.getDefault().getID());

yield on the (my) console (with my local timezone).

2016-09-25 19:26:12
Europe/Paris
Comments