0
String = 26/8/2013 15:59;

I want to convert this date into GMT, however after applying the below code, I get the EEST time rather than the GMT.

DateFormat df = new SimpleDateFormat("dd/MM/yyyy h:m");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
df.parse(newDate);
Log.i(tag, df.parse(newDate).toString());

Output :

Mon Aug 26 18:59:00 EEST 2013

Whats wrong ?

tony9099
  • 4,567
  • 9
  • 44
  • 73

3 Answers3

2

Your parsing is correct, the different is just for your locale time zone that is used to display when you are making toString(). I just used formatted output to demonstrate the correct format . Here is the details example:

final String time = "26/8/2013 15:59";
TimeZone timeZone = TimeZone.getTimeZone("UTC");
final String REQUEST_DATE_FORMAT = "dd/MM/yyyy h:m";

DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
Date localDate = format.parse(time);

// localDate.toString()
// PRINT. Mon Aug 26 15:59:00 EEST 2013

Calendar cal = Calendar.getInstance(timeZone);
cal.setTime(localDate);

format.setTimeZone(timeZone);
final String utcTime = format.format(cal.getTime());
// PRINT. 26/08/2013 12:59
Shamim Ahmmed
  • 8,265
  • 6
  • 25
  • 36
  • @ShamimAhmedd, the difference between my device's locale and GMT is +3.. however I cannot get the GMT behind 3 hours.. – tony9099 Aug 26 '13 at 13:36
  • @tony9099, First you are parsing the date into UTC (15:59) but when you are trying to display it in your in your local format (say, 18:59) which is correct. As you are setting timezone before parsing. But if you will set time zone after parsing the date, you will get UTC=1:59 and local =15:59. You have to make sure what is your source format. UTC or local. – Shamim Ahmmed Aug 26 '13 at 13:48
  • It is local. I would highly appreciate it if you update the code accordingly. to make things more clear : final String time = "26/8/2013 15:59"; < local .... I want this in UTC which is 12:59 – tony9099 Aug 26 '13 at 13:51
0

Nothing's really wrong. You are successfully parsing the datetime string interpreted as UTC timezone.

When printing it to log, you get what you ask for - Date.toString() returns the date formatted to current locale settings which include the timezone. The difference between UTC and EEST is 3 hours.

If you want to to format it to display some other timezone, pass it though format() of a SimpleDateFormat that is configured to the timezone you want.

laalto
  • 150,114
  • 66
  • 286
  • 303
0

I think you should use the below approach: Date myDate = new Date();

Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(myDate);
Date time = calendar.getTime();
SimpleDateFormat outputFmt = new SimpleDateFormat("MMM dd, yyy h:mm a zz");
String dateAsString = outputFmt.format(time);
System.out.println(dateAsString);
sanjeeb
  • 87
  • 1
  • 12