What's the best way to parse an XML dateTime in Java?

What's the best way to parse an XML dateTime in Java? Legal dateTime values include 2002-10-10T12:00:00-05:00 AND 2002-10-10T17:00:00Z

Is there a good open source library I can use, or should I roll my own using SimpleDateFormat or similar?


There's also javax.xml.bind.DatatypeConverter#parseDateTime(String xsdDateTime), which comes as part of the JDK.


I think you want ISODateTimeFormat.dateTimeNoMillis() from Joda Time. In general I would strongly urge you to stay away from the built-in Date/Calendar classes in Java. Joda Time is much better designed, favours immutability (in particular the formatters are immutable and thread-safe) and is the basis for the new date/time API in Java 7.

Sample code:

import org.joda.time.*;
import org.joda.time.format.*;

class Test
{   
    public static void main(String[] args)
    {
        parse("2002-10-10T12:00:00-05:00");
        parse("2002-10-10T17:00:00Z");
    }

    private static final DateTimeFormatter XML_DATE_TIME_FORMAT =
        ISODateTimeFormat.dateTimeNoMillis();

    private static final DateTimeFormatter CHECKING_FORMAT =
        ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC);

    static void parse(String text)
    {
        System.out.println("Parsing: " + text);
        DateTime dt = XML_DATE_TIME_FORMAT.parseDateTime(text);
        System.out.println("Parsed to: " + CHECKING_FORMAT.print(dt));
    }
}

Output:

Parsing: 2002-10-10T12:00:00-05:00
Parsed to: 2002-10-10T17:00:00.000Z
Parsing: 2002-10-10T17:00:00Z
Parsed to: 2002-10-10T17:00:00.000Z

(Note that in the output both end up as the same UTC time. The output formatted uses UTC because we asked it to with the withZone call.)