0

In my Android app I have a string like this, String date = "2016-09-24T06:24:01Z";

I use this code to turn it into a nicer looking date format:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getDefault());
DateFormat formatted = new SimpleDateFormat(format);

Date result = dateFormat.parse(date);
dateString = formatted.format(result);

However it's not applying the timezone. I've tried setting it on both dateFormat and formatted and no matter what I do it still comes back with 6:24 AM.

Shouldn't TimeZone.getDefault() be looking at the timezone on the device running the app and adjusting the time accordingly?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
b85411
  • 9,420
  • 15
  • 65
  • 119

2 Answers2

0

As your are using java.util.date which have no Time Zone. It represent UTC/GMT no Time Zone offset. See below thing.

so change this line

dateFormat.setTimeZone(TimeZone.getDefault());

to this

dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

or this

dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Harshad Pansuriya
  • 20,189
  • 8
  • 67
  • 95
  • But how do I end up getting the `dateString` result to show the the time using whatever the timezone of the device is? – b85411 Oct 06 '16 at 06:51
0

If you know the current time zone:

TimeZone tzone = TimeZone.getTimeZone("America/Los_Angeles");
tzone.setDefault(tzone);

If you do not know the current timezone:

Calendar cal = Calendar.getInstance();
long milliDiff = cal.get(Calendar.ZONE_OFFSET);
// Got local offset, now loop through available timezone id(s).
String [] ids = TimeZone.getAvailableIDs();
String name = null;
for (String id : ids) {
  TimeZone tz = TimeZone.getTimeZone(id);
  if (tz.getRawOffset() == milliDiff) {
    // Found a match.
    name = id;
    break;
  }
}

TimeZone tzone = TimeZone.getTimeZone(name);
tzone.setDefault(tzone);
Wojtek
  • 1,288
  • 11
  • 16
  • I'm not trying to get the current time though. I want to convert `String date = "2016-09-24T06:24:01Z";` into a nice string, and have that result use the local timezone. – b85411 Oct 06 '16 at 07:58