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

后端 未结 9 1033
刺人心
刺人心 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:31

    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.)

提交回复
热议问题