0

I am trying to convert the xmlGregorianCalendar to Date. But the output is reducing the date by a day. The below is the code I use - xmlGregorianCalendar is passed as 2019-04-02Z , But when the below line is executed its returns the date as - Mon Apr 01 19:00:00 CDT 2019

private Date formatDate(XMLGregorianCalendar xmlGregorianCalendar) {

    if(null != xmlGregorianCalendar ) {
        return xmlGregorianCalendar.toGregorianCalendar().getTime();
    } 
    return null;
}

Not sure what am I doing wrong.

Hero
  • 639
  • 4
  • 12
  • 33
  • The value is being skewed by time zone. You need to account for time zone. – Andreas Apr 02 '19 at 20:38
  • `04/02/2019` is not a valid XML date string. Did you mean that XML value is `2019-04-02`? – Andreas Apr 02 '19 at 20:39
  • @Andreas Updated the Question - date is passed as 2019-04-02Z but converted as - Mon Apr 01 19:00:00 CDT 2019 – Hero Apr 02 '19 at 20:41
  • As I said, the `2019-04-02Z` value (in UTC time zone) is being converted to 4/1/2019 at 7:00 PM in Central Time Zone, which is correct. To get correct date value, *you* must specify time zone of UTC when formatting the date value for display. – Andreas Apr 02 '19 at 20:43
  • 2
    I would suggest you start using `java.time.LocalDate` for date-only values, instead of the outdated `java.util.Date` class. See [Convert between LocalDate and XMLGregorianCalendar](https://stackoverflow.com/q/29767084/5221149) for how to convert correctly. – Andreas Apr 02 '19 at 20:45
  • 2
    @Andreas - used localDate to get desired result. Thanks – Hero Apr 02 '19 at 23:56
  • Oh, the trouble with the good old, no, bad old `Date` class again. No one should be using that anymore. Glad that the modern `LocalDate` helped you out. – Ole V.V. Apr 03 '19 at 03:48

1 Answers1

0

Try to use this:

return xmlGregorianCalendar
    .toGregorianCalendar(TimeZone.getTimeZone("Coordinated Universal Time"), null, null)
    .getTime();