如何将ISO 8601日期时间字符串转换为java.util.LocalDateTime? [英] How do I convert an ISO 8601 date time String to java.util.LocalDateTime?
问题描述
我正在从Wikidata中读取数据.它们代表使用ISO 8601规范的时间点属性P585.但是,相同的生物带有+.
如果我使用的是Joda,那么将String转换为joda dateTime将会非常简单.
new DateTime(dateTime, DateTimeZone.UTC);
但是,当我执行LocalDateTime.parse("+2017-02-26T00:00:00Z")
时,出现一个错误,提示无法解析索引0处的字符.在Java 8中是否有此原因.Joda可以轻松地做到这一点而没有任何错误.
我也尝试过LocalDateTime.parse("+2017-02-26T00:00:00Z", DateTimeFormatter.ISO_DATE_TIME)
,但是徒劳.
我们如何绕过加号而不必通过字符串操作将其删除?
Java的DateTimeFormatter
类可能会有所帮助.以下是一些我认为可以解决您的问题的示例代码(或至少为您提供了一些思考):
class DateTimeTester {
---
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("+yyyy-MM-dd'T'HH:mm:ss'Z'")
.withZone(ZoneId.of("UTC"));
LocalDateTime date = LocalDateTime.parse("+2017-02-26T01:02:03Z", formatter);
System.out.println(date);
}
}
请参阅 Wikidata的可用数据类型列表关于time
数据类型:
"时间点的显式值,表示为时间戳记 类似 ISO 8601,例如+ 2013-01-01T00:00:00Z.年份始终签名并填充为4到16位数字.".
因此Wikidata的time
数据类型仅类似于 ISO8601.
如果您的代码需要处理负数年(在0年之前),则需要相应地调整我建议的解决方案.
I am reading data from Wikidata. They represent their point in time property, P585 using ISO 8601 spec. However, the same beings with a +.
If I were using Joda then converting the String to joda dateTime would have been very simple.
new DateTime(dateTime, DateTimeZone.UTC);
However, when I do LocalDateTime.parse("+2017-02-26T00:00:00Z")
I get an error saying can't parse the character at index 0. Is there a reason for this in Java 8. Joda does it pretty easily without any errors.
I also tried LocalDateTime.parse("+2017-02-26T00:00:00Z", DateTimeFormatter.ISO_DATE_TIME)
but in vain.
How do we get around the Plus sign without having to remove it by string manipulation?
Java's DateTimeFormatter
class may be of help. Here is some sample code that I believe addressses your problem (or at least gives you something to think about):
class DateTimeTester {
---
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("+yyyy-MM-dd'T'HH:mm:ss'Z'")
.withZone(ZoneId.of("UTC"));
LocalDateTime date = LocalDateTime.parse("+2017-02-26T01:02:03Z", formatter);
System.out.println(date);
}
}
Refer to the section called Patterns for Formatting and Parsing in the javadoc for DateTimeFormatter for details about the format-string passed to DateTimeFormatter.ofPattern()
.
Something to note:
Wikidata's list of available data types says about the time
data type:
"explicit value for point in time, represented as a timestamp resembling ISO 8601, e.g. +2013-01-01T00:00:00Z. The year is always signed and padded to have between 4 and 16 digits.".
So Wikidata's time
data type only resembles ISO 8601.
If your code needs to handle negative years (before year 0), you will need to adjust my suggested solution accordingly.
这篇关于如何将ISO 8601日期时间字符串转换为java.util.LocalDateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!