Easy when you know how.
String receivedDateTimeString = "2020-04-13T12:36:13Z";
XMLGregorianCalendar xmlgc = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(receivedDateTimeString);
System.out.println(xmlgc);
Output:
2020-04-13T12:36:13Z
ZonedDateTime.toString()
sometimes produces ISO 8601 format (and sometimes an extended format with a zone ID that is not part of ISO 8601). In your case you have got pure ISO 8601. Dates and times in XML documents use a variant of ISO 8601, it’s close enough that we can consider them the same for our purpose here. So an XMLGregorianCalendar
instance is created directly from the ISO 8601 string, and its toString
method produces the same ISO 8601 string back.
ThreeTen Backport allows you to use ZonedDateTime in Java 7
You can, and you may prefer to use ZonedDateTime
in Java 7 too rather than XMLGregorianCalendar
. This use goes through ThreeTen Backport, the backport of java.time to Java 6 and 7, see the links at the bottom.
import org.threeten.bp.ZonedDateTime;
public class DemoZonedDateTimeInJava7 {
public static void main(String[] args) {
String receivedDateTimeString = "2020-04-13T12:36:13Z";
ZonedDateTime zdt = ZonedDateTime.parse(receivedDateTimeString);
System.out.println(zdt);
}
}
2020-04-13T12:36:13Z
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links