Saturday, January 17, 2015

Parsing ISO 8601-compliant String to java.util.Date

To parse a string representation of date in ISO 8601 format, for example, 2015-01-18T01:01:01Z, you can use javax.xml.bind.DatatypeConverter class (included in JDK since version 1.6 update 4). The class is part of JAXB API. Please see JAXB for more details.

Please see the code snippet below on how to use it.
System.out.println(DatatypeConverter.parseDateTime("2014-10-15T01:01:01Z").getTime());
The parseDateTime() method returns java.util.Calendar object.



Why not use java.text.SimpleDateFormat class?

The example below works the same.
SimpleDateFormat formatter = new SimplateDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
System.out.println(formatter.parse("2014-10-15T01:01:01Z").getTime());
But the ParseException will be thrown if the date string is in another ISO 8601 format, for example, "2014-10-15T01:01:01+07:00". DatatypeConverter still works for this format and other ISO 8601 formats.





Reference
https://jaxb.java.net/tutorial/section_1_1-Introduction.html#About JAXB
https://jaxb.java.net/guide/Which_JAXB_RI_is_included_in_which_JDK_.html

No comments:

Post a Comment