Convert JAXBElement<XMLGregorianCalendar> to OffsetDateTime

喜你入骨 提交于 2021-02-04 08:31:06

问题


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.

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)

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.

Could anyone pls help to get the desired conversion of dateTime.


回答1:


tl;dr

myXMLGregorianCalendar
.toGregorianCalendar()
.toZonedDateTime()
.format( 
    DateTimeFormatter.ISO_OFFSET_DATE_TIME 
)

Details

Convert an XMLGregorianCalendar legacy object to another legacy class, GregorianCalendar as an intermediate step.

GregorianCalendar gc = myXMLGregorianCalendar.toGregorianCalendar() ;

Convert to the modern class.

ZonedDateTime zdt = gc.toZonedDateTime() ;

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 ) ;

But if you want to see that same moment adjusted to UTC, just extract a Instant.

Instant instant = zdt.toInstant() ;

If you need the more flexible OffsetDateTime class, apply an offset.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;


来源:https://stackoverflow.com/questions/57448018/convert-jaxbelementxmlgregoriancalendar-to-offsetdatetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!