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

后端 未结 9 1030
刺人心
刺人心 2020-11-28 06:16

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

9条回答
  •  醉话见心
    2020-11-28 06:57

    StaxMan is absolutely correct. In order to use SimpleDateFormat, you need to turn off lax parsing in each SimpleDateFormat and iterate over several SimpleDateFormat formats until you find the one that parses the date without throwing an exception. If you leave lax parsing on, you are prone to get a match when you didn't really want one, and the lexical space of XSD:DateTime leaves some flexibility in format that SimpleDateFormat can't handle in a single expression.

    XML Schema 1.0 does indeed use ISO 8601, which Joda Time, as suggested by Jon Skeet, implements so that is a valid option.

    If you want to keep it all in the native Java packages, you can also use XMLGregorianCalendar in conjunction with DatatypeFactory to parse and create XSD:Datetime strings.

    See DatatypeFactory.newXMLGregorianCalendar and XMLGregorianCalendar.toXMLFormat

提交回复
热议问题