问题
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