javastringlocaldatetimedatetimeformatter

Convert String to LocalDateTime Java 8


I'm trying to convert the following String into a LocalDateTime:

String dateStr = "2020-08-17T10:11:16.908732"; 

DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.nnnnnn");
LocalDateTime dateTime = LocalDateTime.parse(dateStr, format);

But I'm hitting the following error:

java.time.format.DateTimeParseException: Text '2020-08-17T10:11:16.908732' could not be parsed at index 10
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)

Can anyone please help to advise how I should be correctly formatting the string into a LocalDateTime?

Many thanks


Solution

  • You don't need to specify a DateTimeFormatter in this case because the default one will be used if you don't pass one at all:

    public static void main(String[] args) {
        String dateStr = "2020-08-17T10:11:16.908732";
        // the following uses the DateTimeFormatter.ISO_LOCAL_DATE_TIME implicitly
        LocalDateTime dateTime = LocalDateTime.parse(dateStr);
        System.out.println(dateTime);
    }
    

    That code will output 2020-08-17T10:11:16.908732.

    If you are insisting on using a custom DateTimeFormatter, consider the T by single-quoting it in the pattern and don't use nanosecond parsing (n) for parsing fractions of second (S), the result might be wrong otherwise.

    Do it like this:

    public static void main(String[] args) {
        String dateStr = "2020-08-17T10:11:16.908732"; 
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
        LocalDateTime dateTime = LocalDateTime.parse(dateStr, format);
        System.out.println(dateTime);
    }
    

    with the same output as above.

    Note:
    The result of using the pattern "yyyy-MM-dd'T'HH:mm:ss.nnnnnn" would not be equal to the parsed String, instead, it would be

    2020-08-17T10:11:16.000908732