我试图将ISO 8601格式的字符串转换为java.util.Date.
yyyy-MM-dd'T'HH:mm:ssZ如果与Locale(比较样本)一起使用,我发现该模式符合ISO8601标准.
但是,使用java.text.SimpleDateFormat,我无法转换格式正确的String 2010-01-01T12:00:00+01:00.我必须先将它转换为2010-01-01T12:00:00+0100没有冒号的.
那么,目前的解决方案是
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));
Run Code Online (Sandbox Code Playgroud)
这显然不是那么好.我错过了什么或者有更好的解决方案吗?
回答
感谢JuanZe的评论,我发现了Joda-Time魔术,这里也有描述.
所以,解决方案是
DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis();
String jtdate = "2010-01-01T12:00:00+01:00";
System.out.println(parser2.parseDateTime(jtdate));
Run Code Online (Sandbox Code Playgroud)
或者更简单地说,通过构造函数使用默认解析器:
DateTime dt = new DateTime( "2010-01-01T12:00:00+01:00" ) ;
Run Code Online (Sandbox Code Playgroud)
对我来说,这很好.
ISO8601Utils由于 SonarQube 抛出以下错误,我正在替换下面评论的内容:Remove this use of "ISO8601Utils"; it is deprecated.要替换它,我将使用外部 json 模式生成器模块,https://github.com/FasterXML/jackson-module-jsonSchema或其他内容。我通读了链接,但不明白如何使用对象映射器来替换这一行:String value = ISO8601Utils.format(date, true);
public static class ISO8601DateFormat extends DateFormat {
public ISO8601DateFormat() {}
public StringBuffer format(Date date, StringBuffer toAppendTo,
FieldPosition fieldPosition) {
String value = ISO8601Utils.format(date, true);
//Im not sure how I can replace this line with a new
//replacement
toAppendTo.append(value);
return toAppendTo;
}
public Date parse(String source, ParsePosition pos) {
pos.setIndex(source.length());
return ISODateTimeFormat.dateTimeParser().parseDateTime(source).toDate();
}
public Object clone() {
return this; …Run Code Online (Sandbox Code Playgroud)