0

I am trying to convert XMLGregorian Calendar to java.util.Date in GMT.But following method gives me same date.It could not convert the date. Can you please look at the below code and tell me where I am doing wrong ?

     try {
        SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:MM");
        dateFormatGmt.setTimeZone(TimeZone.getTimeZone("UTC"));
        return dateFormatGmt.parse(dateFormatGmt.format(date));
    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    }
Tonyukuk
  • 5,745
  • 7
  • 35
  • 63
  • 2
    You can get a `java.util.Date` with `xmlGregorianCalendar.toGregorianCalendar().getTime()`. You don't need to format and parse because the [date doesn't have a timezone](https://codeblog.jonskeet.uk/2017/04/23/all-about-java-util-date), so there's no need to convert it to UTC. A `Date` has only the number of milliseconds since `1970-01-01T00:00Z`, and has no timezone nor any format (you can also think that it's "always in UTC"). –  Aug 15 '17 at 12:58

1 Answers1

0

java.time

Avoid the troublesome old date-time classes, now supplanted by the java.time classes.

Convert your XMLGregorianCalendar object to a java.util.GregorianCalendar. From there to a java.time.ZonedDateTime. From there to a java.time.Instant which is always in UTC (the new GMT, basically).

GregorianCalendar gc = myXgc.toGregorianCalendar() ;
ZonedDateTime zdt = gc.toZonedDateTime() ;
Instant instant = zdt.toInstant() ;

If you absolutely must have a java.util.Date, convert using new methods added to the old classes.

java.util.Date d = Date.from( instant ) ;

Search Stack Overflow for more info. Your Question is really a duplicate of many others.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154