3

Currently the date in my app is stored as an ISO date 2016-08-26T11:03:39.000+01:00.

If the user went to an event at 11:03:39 in the UK, it wouldn't make sense for this time to show 06:03:39 in Florida, USA for example. This is currently happening in my app.

How do I convert the ISO date back to the time the event happened locally no matter where the event happened and where the user is?

Below is the code which I'm currently using.

DateFormat isoDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");
DateFormat timeFormat = new SimpleDateFormat("hh:mm a");
mDate = isoDateFormat.parse(isoDateString);
dateString = dateFormat.format(mDate);
timeString = timeFormat.format(mDate);
Mark O'Sullivan
  • 10,138
  • 6
  • 39
  • 60
  • Are you able to use java.time instead of java.util.Date/Calendar? If so, that should make your life easier... – Jon Skeet Jan 20 '17 at 15:52
  • @JonSkeet not sure. I just need to be able to parse an ISO date string and then convert it so I have a string for the date and a string for the time. – Mark O'Sullivan Jan 20 '17 at 15:57
  • Is this what you are looking for? http://stackoverflow.com/questions/9429357/date-and-time-conversion-to-some-other-timezone-in-java – weston Jan 20 '17 at 16:18

1 Answers1

1

You can do this by getting the offset from the ISO string and getting the timezone from it like so.

import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.TimeZone;
import java.util.Date;

class Main {
  public static void main(String[] args) {
    DateFormat isoDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    //DateFormat isoDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); I needed to use XXX in repl.
    DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");
    DateFormat timeFormat = new SimpleDateFormat("hh:mm a");
    try
    {
      String isoString = "2016-08-26T11:03:39.000+01:00";
      Date mDate = isoDateFormat.parse(isoString);
      System.out.println("GMT" + isoString.substring(23));
      TimeZone mTimeZone = TimeZone.getTimeZone("GMT" + isoString.substring(23));
      dateFormat.setTimeZone(mTimeZone);
      timeFormat.setTimeZone(mTimeZone);
      System.out.println(mTimeZone.toString());
      String dateString = dateFormat.format(mDate);
      String timeString = timeFormat.format(mDate);
      System.out.println(dateString + " " + timeString);
    }
    catch(ParseException e)
    {
       System.out.println("Error");
    }
  }
}

Here's a repl link you can use to play with it.

https://repl.it/FPrN/2

Dave S
  • 3,378
  • 1
  • 20
  • 34