0

I want to convert this date format :

2014-04-23T14:20:00.000-07:00

into a date object so I can use this method to get the difference :

DateUtils.getDateDifference(DATE_OBJECT);

...

I've tried using 'SimpleDateFormat' but it throws an exception, checked the code many times, but doesn't work:

    String pubDate = "2014-04-23T14:20:00.000-07:00";
    SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy kk:mm:ss Z", Locale.ENGLISH);
    try {
        Date pDate =  df.parse(pubDate);
        pubDate = "This post was published " + DateUtils.getDateDifference(pDate);
    } catch (ParseException e) {
        Log.e("DATE PARSING", "Error parsing date..");
        pubDate = "Couldn't be retrieved.";
    } 

What is the simplest way to achieve it successfully?

4

2 回答 2

2

According to Android documentation (link given in comment of @MarcoAcierno) you need the symbol Z five times to parse the timezone offset. Note that in Java-6 there is no built-in solution for handling the colon in offset part, but Java-7 has introduced the new symbol X (here three times: XXX). Another example for (Android != Java). So the final pattern looks like:

SimpleDateFormat sdf =
  new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ");
java.util.Date d = sdf.parse("2014-04-23T14:20:00.000-07:00");

Specifying a Locale is not necessary because your format does not contain any language- or locale-sensitive parts (is just pure ISO-format).

于 2014-04-24T04:36:01.000 回答
0

If you used the excellent Joda-Time library instead of the notoriously troublesome java.util.Date and SimpleTextFormat classes,,you could pass that standard ISO 8601 String directly to a DateTime constructor. Joda-Time uses ISO 8601 for its defaults.

DateTime dateTime = new DateTime( pubDate );
于 2014-04-24T06:39:27.497 回答