3

I'm creating an app on Android which communicates with a server. That server gives me back a ISO 8601 date String, like the following:

2014-11-21 12:24:56.662061-02

Then I'm trying to use Java's SimpleDateFormatter to parse my String, like this:

        Locale l = new Locale("pt","BR");
        Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSSZZ",l).parse(str_date);
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(date.getTime());

Thing is, this solution works partially. I'm able to get the year, month, day and hour correctly, but when it comes down to hours, minutes and seconds I always get the minutes wrong. If I try to print it using my example String, I get something like "12:35" instead of "12:24". I've tried different masks, using a Locale, not using a Locale, and nothing seems to work for me.

I've seen on this link that The SimpleDateFormatter doesn't support ISO 8601 very well, and that guy gave a solution using javax.xml.bind.DatatypeConverter.parseDateTime() method, but the DatatypeConverter is not present on the Android SDK. So... What can I do to parse this String correctly?

Community
  • 1
  • 1
Mauker
  • 11,237
  • 7
  • 58
  • 76
  • 1
    There's a 'T' missing for your example to really be ISO 8601... But your format seems to handle this. The examples for `SimpleDateFormat` uses only a single ´Z´ character, maybe that's the problem? Also, you have too many ´S´s... There's never more than 3 digits so 'SSS' should do. – Harald K Nov 21 '14 at 15:24
  • Well, I've tried many different masks, and the one using the triple S threw an exception. I also tried to use a single Z and it didn't work. – Mauker Nov 21 '14 at 23:07

1 Answers1

4

S is for milliseconds; 662061 is 662 s = 11 minutes.

Somehow throw away the microseconds, and use SSS.

str_date = str_date.replaceFirst("(\\d\\d[\\.,]\\d{3})\\d+", "$1");
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • It worked! I've used your code and changed the mask to "SSSZ" and it worked! Thank you very much! – Mauker Nov 21 '14 at 23:45