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 l
http://xmlbeans.apache.org/samples/DateTime.html
There is XmlDateTime class. Just do XMLDateTime.stringToDate(xmlDateTime).
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.)
In XML Beans v2 it would be XmlDateTime.Factory.parse(dateTimeString)
, but this is awkward because it expects an element with start and end tags like <mytime>2011-10-20T15:07:14.112-07:00</mytime>
An easier approach is to call (new org.apache.xmlbeans.GDate(dateTimeString)).getDate()
.
See Parse and format dateTime values, although: -It takes "GMT" as the default timezone -It does not complain if there are trailing non-parseable parts -Does not take into account that TimeZone defaults to "GMT" on wrong "GMT+xxxx"
You can also use newXMLGregorianCalendar in javax.xml.datatype.DatatypeFactory
, which gives you detailed control, including detecting whether the timezone was specified or not.
There's also javax.xml.bind.DatatypeConverter#parseDateTime(String xsdDateTime), which comes as part of the JDK.