1

I get a string value of time in GMT format like this: "2000-01-01T12:00:00.000Z" and I want to convert it to some readable date/time format. I don't know how to do it

I'm using the following code but it doesn't seems to work

        schedules = matrix.get("schedules").getAsJsonArray();
        schedules_array = schedules.get(0).getAsJsonObject();
        final String open = schedules_array.get("open").getAsString();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        try {
            Date date = format.parse(open);
            Log.d("OPEN", String.valueOf(date));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
Phantom_strike
  • 149
  • 2
  • 10
  • Please search Stack Overflow before posting. This topic has been addressed many many times already. Also, you are using troublesome legacy classes now supplanted by java.time classes. See the ThreeTenABP project for Android. – Basil Bourque Apr 15 '17 at 23:59

1 Answers1

4

First, since your input has milliseconds, fix the format string:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

You then have two choices:

  1. Add the following statement before calling parse():

    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    
  2. Change the format to use the time zone in the input string:

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
    

I would suggest the second one.

Andreas
  • 154,647
  • 11
  • 152
  • 247