转换JAXBElement< XMLGregorianCalendar>到OffsetDateTime [英] Convert JAXBElement<XMLGregorianCalendar> to OffsetDateTime
问题描述
我正在尝试将JAXBElement-XMLGregorianCalendar转换为offsetDateTime.我能够做到这一点,但我想将日期转换为特定格式.
I am trying to convert the JAXBElement-XMLGregorianCalendar to offsetDateTime. I am able to do that but i want to convert the date in a particular format.
我正在转换的代码:calendarValue是2016-03-25T00:00:00 + 05:30,但我需要将类型转换为offsetDateTime,所以我在转换以下进行操作
Code i am using to convert : calendarValue is 2016-03-25T00:00:00+05:30 but i need to covert the type to offsetDateTime so i am doing below conversion
calendarValue.toGregorianCalendar().getTime().toInstant().atOffset(ZoneOffset.UTC)
作为响应,我将转换后的值转换为:2016-03-24T18:30:00Z,而我希望将转换后的值转换为:2016-03-25T00:00:00 + 05:30.
In response i am getting the value after converting as : 2016-03-24T18:30:00Z while i want the converted value as : 2016-03-25T00:00:00+05:30.
任何人都可以帮助获得所需的dateTime转换.
Could anyone pls help to get the desired conversion of dateTime.
推荐答案
tl; dr
myXMLGregorianCalendar
.toGregorianCalendar()
.toZonedDateTime()
.format(
DateTimeFormatter.ISO_OFFSET_DATE_TIME
)
详细信息
将 XMLGregorianCalendar
传统对象转换为另一个传统类 GregorianCalendar
作为中间步骤.
Details
Convert an XMLGregorianCalendar
legacy object to another legacy class, GregorianCalendar
as an intermediate step.
GregorianCalendar gc = myXMLGregorianCalendar.toGregorianCalendar() ;
转换为现代班.
ZonedDateTime zdt = gc.toZonedDateTime() ;
此 ZonedDateTime
对象可能满足您的需求.
This ZonedDateTime
object may meet your needs.
以所需的格式生成表示该时刻值的字符串,尽管不幸的是,格式会掩盖时区的名称,这是有价值的信息.
Generate a string representing the value of this moment in your desired format, though your format unfortunately masks the name of the time zone which is valuable information.
String output = zdt.format( DateTimeFormatter.ISO_OFFSET_DATE_TIME ) ;
但是,如果您希望将同一时刻调整为UTC,只需提取一个 Instant
.
But if you want to see that same moment adjusted to UTC, just extract a Instant
.
Instant instant = zdt.toInstant() ;
如果您需要更灵活的 OffsetDateTime
类,请应用一个偏移量.
If you need the more flexible OffsetDateTime
class, apply an offset.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
这篇关于转换JAXBElement< XMLGregorianCalendar>到OffsetDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!