Reputation: 31
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 convert 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
.
Upvotes: 1
Views: 5633
Reputation: 340118
myXMLGregorianCalendar
.toGregorianCalendar()
.toZonedDateTime()
.format(
DateTimeFormatter.ISO_OFFSET_DATE_TIME
)
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 ) ;
Upvotes: 4