Java – How to parse ISO 8601 strings to Java dates on Android

How to parse ISO 8601 strings to Java dates on Android… here is a solution to the problem.

How to parse ISO 8601 strings to Java dates on Android

I’m creating an app on Android that communicates with the server. The server returned me ISO 8601 date string as follows:

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

Then I tried parsing my string using Java’s SimpleDateFormatter as follows:

        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 truth is that this solution partially works. I was able to get the year, month, day, and hour correctly, but I always got the minute wrong when it came to hours, minutes, and seconds. If I try to print it with my example string, I get something like “12:35” instead of “12:24”. I tried a different mask, using the locale, not using the locale, but nothing seems to work for me.

I’m in this < a href="https://stackoverflow.com/questions/2201925/converting-iso-8601-compliant-string-to-java-util-date" rel="noreferrer noopener nofollow" >link I saw that SimpleDateFormatter does not support ISO 8601 well, and the person who gave a solution using the javax.xml.bind.DatatypeConverter.parseDateTime() method, but DatatypeConverter does not exist on the Android SDK. So… What can I do to parse this string correctly?

Related Problems and Solutions