Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 converting the String to joda dateTime would have been very simple.

new DateTime(dateTime, DateTimeZone.UTC);

However, when I do LocalDateTime.parse("+2017-02-26T00:00:00Z") I get an error saying can't parse the character at index 0. Is there a reason for this in Java 8. Joda does it pretty easily without any errors.

I also tried LocalDateTime.parse("+2017-02-26T00:00:00Z", DateTimeFormatter.ISO_DATE_TIME) but in vain.

How do we get around the Plus sign without having to remove it by string manipulation?

like image 817
dhamechaSpeaks Avatar asked Feb 02 '17 01:02

dhamechaSpeaks


1 Answers

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.

like image 141
StvnBrkdll Avatar answered Sep 28 '22 06:09

StvnBrkdll