2016-11-09 31 views
1

当使用Google搜索时,我遇到了很多答案 - 因此是个问题。将xsd:date解析为LocalDate的正确方法

什么是解析任何xsd:dateLocalDate在Java中正确方法是什么?

这里是我想出的办法(从谷歌搜索):

DatatypeFactory.newInstance() 
    .newXMLGregorianCalendar(str) 
    .toGregorianCalendar() 
    .toZonedDateTime() 
    .toLocalDate() 

另:

DatatypeConverter.parseDate(str) 
    .toInstant() 
    .atZone(ZoneId.systemDefault()) 
    .toLocalDate() 

也许我应该做的完全不同的东西?

+0

这有帮助吗? http://stackoverflow.com/questions/7519800/apache-axis-calendar-instance-that-gets-serialized-to-0001-01-01t000000-000z – kaqqao

+0

@kaqqao - 我不相信它...... – Cheetah

回答

0

没有,有没有办法正确转换任何xsd:dateLocalDate

因为xsd:date可能有时区并且LocalDate没有时区。所以要么不是任何xsd:date或转换不完全是正确

如果你有丢失时区OK,然后我只是做:

XMLGregorianCalendar cal = DatatypeFactory.newInstance().newXMLGregorianCalendar(str); 
LocalDate localDate = LocalDate.of(cal.getYear(), cal.getMonth(), cal.getDay()); 

我见过一对夫妇它通过GregorianCalendarZonedDateTime做到这一点的答案,但我不明白为什么有这种间接性,如果你打算失去时区。

我还认为,通过XMLGregorianCalendar解析比通过CalendarDatatypeConverter.parseDate因为XMLGregorianCalendar更好更接近的xsd:date的词汇值。 LocalDate需要的只是年,月和日,所以选择这些值的最短路径是合理的。

+0

因此,我的第一个例子会释放时区信息,尽管它首先被转换为ZonedDateTime,然后转换为LocalDate(大概ZonedDateTime已经被转换为LocalDateTime)。 – Cheetah

+0

@Cheetah LocalDate [不存储或表示时间或时区](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html),句点。所以当然,如果你最终转换为'LocalDate',那么你会失去时区,无论你在途中会得到哪些结果。 – lexicore

+0

我明白你在说什么。我的问题其实是不正确的。我的问题应该是:“我应该如何最好地从存储在LocalDate对象中的xsd:date中取出日期组件?” – Cheetah