如何在Android上解析ISO 8601字符串到Java日期 [英] How to parse a ISO 8601 String to Java Date on Android
问题描述
我正在Android上创建一个与服务器通信的应用程序。该服务器给我一个 ISO 8601 日期字符串,如下所示:
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
然后我试图使用Java的SimpleDateFormatter来解析我的String,如下所示:
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());
这个解决方案是有效的。我能够正确地获得年,月,日,时间,但是当它归结到几小时,几分钟和几秒钟时,我总是弄错分钟。如果我尝试使用我的示例String打印它,我会得到像12:35而不是12:24。我尝试过不同的面具,使用区域设置,不使用区域设置,对我来说似乎没有任何效果。
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.
我已经看到这个链接 SimpleDateFormatter不支持ISO 8601,而且家伙使用javax.xml.bind.DatatypeConverter.parseDateTime()方法提供了一个解决方案,但Android SDK中不存在DatatypeConverter。所以...我可以如何正确解析这个String?
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?
推荐答案
S
是毫秒; 662061是662 s = 11分钟。
S
is for milliseconds; 662061 is 662 s = 11 minutes.
不知何故扔掉微秒,并使用SSS。
Somehow throw away the microseconds, and use SSS.
str_date = str_date.replaceFirst("(\\d\\d[\\.,]\\d{3})\\d+", "$1");
这篇关于如何在Android上解析ISO 8601字符串到Java日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!