How to parse ISO 8601 string to Java Date on Android

I am creating an Android application that communicates with a server. This server returns me an ISO 8601 date String like below:

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

Then I try to use Java's SimpleDateFormatter to parse my string like:

        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());

      

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

I saw on this link that SimpleDateFormatter does not support ISO 8601 very well and this guy gave a solution using javax.xml.bind.DatatypeConverter.parseDateTime (), but DatatypeConverter is missing from Android SDK. So ... what can I do to parse this line correctly?

+3


source to share


1 answer


S

- milliseconds; 662061 - 662 s = 11 minutes.

Somehow throw away microseconds and use SSS.



str_date = str_date.replaceFirst("(\\d\\d[\\.,]\\d{3})\\d+", "$1");

      

+4


source







All Articles