0

I have a String from Json like this 2015-05-07T17:00:00Z

I use Eclipse to build android application

how can I parse it to Date? I don't know what is "T" and "Z".

I usually convert a Date like this..but how with string like "2015-05-07T17:00:00Z"?

or must I using split to split "-" ,"T", ":" and "Z"?

Date today = new Date()
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy")
Date todayf = formatter.format(today)
singhakash
  • 7,891
  • 6
  • 31
  • 65

2 Answers2

1

The Z is UTC time. The T is a literal that is used to separate the date from the time, . If your strings always have a "Z"then use:

SimpleDateFormat formatter = new SimpleDateFormat(
    "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date todayf = formattter.format(today);

More here

Community
  • 1
  • 1
alainlompo
  • 4,414
  • 4
  • 32
  • 41
0

Let me know if the following code works for you:

    public static void main(String[] args) {
        Date date = parseJSONDateTime("2015-05-07T17:00:00Z");
        System.out.println(date);
    }

    public static Date parseJSONDateTime(String jsonDateString) {
        if (jsonDateString == null) return null;
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
        if (jsonDateString.contains("T")) jsonDateString = jsonDateString.replace('T', ' ');
        if (jsonDateString.contains("Z")) jsonDateString = jsonDateString.replace("Z", "+0000");
        else
            jsonDateString = jsonDateString.substring(0, jsonDateString.lastIndexOf(':')) + jsonDateString.substring(jsonDateString.lastIndexOf(':')+1);
        try {
            return fmt.parse(jsonDateString);
        }
        catch (ParseException e) {
            e.printStackTrace(); return null;
        }
    }

This code will remove T and replace Z with +0000 and then parse the date accordingly.

akhil_mittal
  • 23,309
  • 7
  • 96
  • 95