问题:
I am trying to convert an ISO 8601 formatted String to a java.util.Date
. 我正在尝试将ISO 8601格式的String转换为java.util.Date
。
I found the pattern yyyy-MM-dd'T'HH:mm:ssZ
to be ISO8601-compliant if used with a Locale (compare sample). 如果与区域设置(比较示例)一起使用,我发现模式yyyy-MM-dd'T'HH:mm:ssZ
符合ISO8601。
However, using the java.text.SimpleDateFormat
, I cannot convert the correctly formatted String 2010-01-01T12:00:00+01:00
. 但是,使用java.text.SimpleDateFormat
不能转换格式正确的String 2010-01-01T12:00:00+01:00
。 I have to convert it first to 2010-01-01T12:00:00+0100
, without the colon. 我必须先将其转换为2010-01-01T12:00:00+0100
,而不能使用冒号。
So, the current solution is 所以,目前的解决方案是
SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.GERMANY);
String date = "2010-01-01T12:00:00+01:00".replaceAll("\\+0([0-9]){1}\\:00", "+0$100");
System.out.println(ISO8601DATEFORMAT.parse(date));
which obviously isn't that nice. 显然不是那么好。 Am I missing something or is there a better solution? 我是否缺少某些东西或有更好的解决方案?
Answer 回答
Thanks to JuanZe's comment, I found the Joda-Time magic, it is also described here . 感谢JuanZe的评论,我找到了Joda-Time魔术, 这里也对此进行了描述 。
So, the solution is 因此,解决方案是
DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis();
String jtdate = "2010-01-01T12:00:00+01:00";
System.out.println(parser2.parseDateTime(jtdate));
Or more simply, use the default parser via the constructor: 或更简单地说,通过构造函数使用默认解析器:
DateTime dt = new DateTime( "2010-01-01T12:00:00+01:00" ) ;
To me, this is nice. 对我来说,这很好。
解决方案:
参考一: https://stackoom.com/question/9Eov/将符合ISO-的字符串转换为java-util-Date参考二: https://oldbug.net/q/9Eov/Converting-ISO-8601-compliant-String-to-java-util-Date
来源:oschina
链接:https://my.oschina.net/u/4432649/blog/4365963