How do I convert an ISO 8601 date time String to java.util.LocalDateTime?

前端 未结 1 1294
春和景丽
春和景丽 2021-01-06 13:17

I am reading data from Wikidata. They represent their point in time property, P585 using ISO 8601 spec. However, the same beings with a +.

If I were using Joda then

相关标签:
1条回答
  • 2021-01-06 13:53

    Java's DateTimeFormatter class may be of help. Here is some sample code that I believe addressses your problem (or at least gives you something to think about):

    class DateTimeTester {
      ---
      public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("+yyyy-MM-dd'T'HH:mm:ss'Z'")
            .withZone(ZoneId.of("UTC"));
        LocalDateTime date = LocalDateTime.parse("+2017-02-26T01:02:03Z", formatter);
        System.out.println(date);
      }
    }
    

    Refer to the section called Patterns for Formatting and Parsing in the javadoc for DateTimeFormatter for details about the format-string passed to DateTimeFormatter.ofPattern().

    Something to note:

    Wikidata's list of available data types says about the time data type:

    "explicit value for point in time, represented as a timestamp resembling ISO 8601, e.g. +2013-01-01T00:00:00Z. The year is always signed and padded to have between 4 and 16 digits.".

    So Wikidata's time data type only resembles ISO 8601.

    If your code needs to handle negative years (before year 0), you will need to adjust my suggested solution accordingly.

    0 讨论(0)
提交回复
热议问题