ISO 8601
That format is one of a family of date-time string formats defined by the ISO 8601 standard.
Python
Looks like many duplicates of your Question for Python.
Search Stack Overflow for: Python "ISO 8601". Get 233 hits.
java.time
On the Java side, you are working too hard. And you are using troublesome old legacy classes now supplanted by the java.time classes.
The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values. So no need to define a formatting pattern. Note that Java 8 has some bugs or limitations with parsing all variations of ISO 8601, remedied in Java 9.
String input = "2016-09-20T01:28:03.238+02:00" ;
OffsetDateTime odt = OffsetDateTime.parse ( input ) ;
Ditto, for going the other direction in ISO 8601 format, no need to define a formatting pattern.
String output = odt.toString () ; // 2016-09-20T01:28:03.238+02:00
If you really need a java.util.Date
for old code not yet updated to the java.time types, you can convert using new methods added to the old classes.
Fractional second
Beware of the fractional second.
- The java.time classes handle values with up to nanosecond resolution, nine digits of decimal fraction.
- The Python
datetime
type seems to have a microseconds resolution, for six decimal places.
- The old legacy date-time classes in Java are limited to millisecond resolution, for three digits of decimal fraction.
- The ISO 8601 standard prescribes no limit to the fraction, any number of decimal fraction digits.
When going from Python to Java, this is another reason to avoid the old date-time classes and stick with java.time classes. When going from Java to python, you may want to truncate any nanoseconds value to microseconds as defined by ChronoUnit.MICROS
.
Instant instant = Instant.now().truncatedTo( ChronoUnit.MICROS ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.