2009-11-27

get an iso-8601 string in Java

Will they ever get it right. The Date handling in Java is a funny story but here is one way to get an ISO-8601 compatible date/time string.


GregorianCalendar cal = new GregorianCalendar(new Locale("sv", "SE"));
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String tmpTime = formatter.format(cal.getTime());
tmpTime = tmpTime.replaceAll("\\+0000$", "Z");
tmpTime = tmpTime.replaceAll("(\\d\\d)$", ":$1");

5 comments:

  1. http://joda-time.sourceforge.net/cal_iso.html

    or maybe...

    GregorianCalendar cal = new GregorianCalendar(new Locale("sv", "SE"));

    XMLGregorianCalendarImpl xmlCal = new com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl(cal);
    System.out.println(xmlCal.toString());

    ReplyDelete
  2. The reason I wrote the code was to present a date-time as a string in a GUI. The string later got converted to a JAXBElement using XMLGregorianCalendar :-)

    ReplyDelete
  3. javax.xml.bind.DataTypeConverter#parseDateTime(String)

    ReplyDelete
  4. As you say, the XMLGregorianCalendar is the place to look. It seems that DataTypeConverter uses the XMLGregorian calendar internally.

    Now I need to parse a date in Atom/XML on Android API level 7 which does not have DataTypeConverter, it is available on API level 8 only :-) So I'll probably use the SimpleDateFormatter again, parrying for the brokenendness of java putting +0000 instead of a Z for UTC time.

    Will they ever get it right :-)

    ReplyDelete
  5. This comment has been removed by a blog administrator.

    ReplyDelete

Note: only a member of this blog may post a comment.