Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a ISO 8601 String to Java Date on Android [duplicate]

Tags:

java

date

android

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?

like image 578
Mauker Avatar asked Aug 27 '26 13:08

Mauker


1 Answers

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");
like image 178
Joop Eggen Avatar answered Aug 30 '26 03:08

Joop Eggen