java.time
DateTimeFormatter requiredFormatter
= DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
.withLocale(Locale.FRENCH);
String originalDateTimeString = "2019-04-11T05:00:54.000+01:00";
OffsetDateTime dateTime = OffsetDateTime.parse(originalDateTimeString);
String requiredDate = dateTime.format(requiredFormatter);
System.out.println("requiredDate: " + requiredDate);
Output from this snippet is (on Java 9.0.4):
requiredDate: 11/04/2019 05:00
Use Java’s built-in localized date and time formats. Don’t bother with rolling your own formatter through a format pattern string. In most cases Java knows better what your audience expects, writing a format pattern string is error-prone, and code using a built-in format lends itself better to porting to a different locale. I don’t know whether your desired locale is French, of course, since many other locales fit the format you asked for, dd/mm/yyyy HH:mm
, too. Just pick the locale that is right for your situation.
The date/time classes you tried to use, XMLGregorianCalendar
and SimpleDateFormat
, are old now, and the latter notoriously troublesome, so you shouldn’t use those if you can avoid it (which you can). Instead I am using java.time, the modern Java date and time API.
What went wrong in your code?
- Minor point, variable names in Java begin with a small letter, so your variable should be called
dateTime
or datetime
.
You cannot assign a string (like "2019-04-11T05:00:54.000+01:00"
) to a variable of type XMLGregorianCalendar
. This is what your error message is trying to tell you. The correct way to convert would have been the one already shown in zmr’s answer:
XMLGregorianCalendar dateTime = DatatypeFactory.newInstance()
.newXMLGregorianCalendar("2019-04-11T05:00:54.000+01:00");
A SimpleDateFormat
cannot format an XMLGregorianCalendar
. The code compiles, but at runtime you get a java.lang.IllegalArgumentException: Cannot format given Object as a Date
.
Link
Oracle tutorial: Date Time explaining how to use java.time.