简体   繁体   中英

Convert JAXBElement<XMLGregorianCalendar> to 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM