Umbrella_Programmer
Umbrella_Programmer

Reputation: 191

Strange results when converting XMLGregorianCalendar to LocalDateTime

I'm trying to convert an XMLGregorianCalendarObject to LocalDateTime and I'm getting unusual results. I have already tried the solutions in this post and this post.

I'm making a few assumptions here that I could be wrong about:

1) the xmlDate argument is UTC

2) the return value is PST

private LocalDateTime convertDate(XMLGregorianCalendar xmlDate) {

   GregorianCalendar gc = xmlDate.toGregorianCalendar();
   ZonedDateTime zdt = gc.toZonedDateTime();
   LocalDateTime localDate = zdt.withZoneSameInstant(ZoneId.of("America/Los_Angeles")).toLocalDateTime();

   return localDate;
   }

The output is exactly the same as the input:

XMLGregorianCalendar xmlDate: "2019-09-03T13:22:38.436-07:00"

LocalDateTime localDate: "2019-09-03T13:22:38"

Also, this does not work (same method, different syntax):

private LocalDateTime convertDate(XMLGregorianCalendar xmlDate) {
    ZonedDateTime utcZoned = xmlDate.toGregorianCalendar().toZonedDateTime().withZoneSameInstant(ZoneId.of("America/Los_Angeles"));
    LocalDateTime localDate = utcZoned.toLocalDateTime();

    return localDate;
}

The result is the same as the first code snippet.

I think my issue is somewhere in the withZoneSameInstant() method. The strange thing is, when I feed a different timezone code into the parameter, conversion does occur. Try it with "Pacific/Auckland".

What am I doing wrong?

Upvotes: 2

Views: 262

Answers (1)

Anonymous
Anonymous

Reputation: 86148

Your first assumption is wrong:

1) the xmlDate argument is UTC

The -07:00 at the end of 2019-09-03T13:22:38.436-07:00 is an offset from UTC. The offset agrees with America/Los_Angeles time zone (Pacific Daylight Time). Java recognizes this, so exactly when you convert to America/Los_Angeles, it doesn’t change the time. When you convert to Pacific/Auckland instead, it does.

I believe that your code is correct.

Upvotes: 3

Related Questions