1

I am getting some data from the server and part of that data is a date. The date is in UTC format. I am showing time to the user in relative time using getRelativeTimeSpanString.

Question

How can I convert a UTC time to the local time zone set on the users device.

This is how I'm getting date from server and using relativeTimeSpanString

 Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH).
                                    parse("2014-05-21 12:21:41");
 Date currentDate = new Date();
 CharSequence cs =  DateUtils.getRelativeTimeSpanString(date.getTime(), currentDate.getTime(), DateUtils.SECOND_IN_MILLIS);
Anthony
  • 33,838
  • 42
  • 169
  • 278

1 Answers1

1

Try something like this. It takes the timezone into consideration as well as Daylight Savings.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
Date date = sdf.parse("2014-05-21 12:21:41");
TimeZone tz = TimeZone.getDefault();
int currentOffsetFromUTC = tz.getRawOffset() + (tz.inDaylightTime(date) ? tz.getDSTSavings() : 0);
String result = sdf.format(date.getTime() + currentOffsetFromUTC);
Squonk
  • 48,735
  • 19
  • 103
  • 135
  • what is `format.format` ? – Anthony May 22 '14 at 15:28
  • Ooops, sorry. Edit on its way. – Squonk May 22 '14 at 15:29
  • ah i think you meant `sdf.format`. So should I be using `getRelativeTimeSpanString` on `date`? – Anthony May 22 '14 at 15:29
  • Yes, I copied that from another answer I posted some time ago and the OP was using `format` but I used `sdf`. With the code above you should get a valid string in the form a user expects it for their own locale. – Squonk May 22 '14 at 15:31
  • great. So, I'm using `DateUtils.getRelativeTimeSpanString(date.getTime()+currentOffsetFromUTC, currentDate.getTime(), DateUtils.SECOND_IN_MILLIS);` will report back how it works :) – Anthony May 22 '14 at 15:32