An example of converting a String to LocalDateTime, but it prompts the following errors:
Java8Example.java
package com.favtuts.time;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class ParseDateWithoutTime {
public static void main(String[] args) {
parseDateFailed();
}
static void parseDateFailed() {
String str = "31-Aug-2020";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.US);
LocalDateTime localDateTime = LocalDateTime.parse(str, dtf);
System.out.println(localDateTime);
}
}
Output
Exception in thread "main" java.time.format.DateTimeParseException: Text '31-Aug-2020' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2020-08-31 of type java.time.format.Parsed
at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2017)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1952)
at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
at com.favtuts.time.ParseDateWithoutTime.parseDateFailed(ParseDateWithoutTime.java:18)
at com.favtuts.time.ParseDateWithoutTime.main(ParseDateWithoutTime.java:10)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2020-08-31 of type java.time.format.Parsed
at java.base/java.time.LocalDateTime.from(LocalDateTime.java:461)
at java.base/java.time.format.Parsed.query(Parsed.java:235)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
... 3 more
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {},ISO resolved to 2020-08-31 of type java.time.format.Parsed
at java.base/java.time.LocalTime.from(LocalTime.java:431)
at java.base/java.time.LocalDateTime.from(LocalDateTime.java:457)
... 5 more
Solution
The date 31-Aug-2020 contains no time, to fix it, uses LocalDate.parse(str, dtf).atStartOfDay()
package com.favtuts.time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class ParseDateWithoutTime {
public static void main(String[] args) {
parseDateSuccess();
}
static void parseDateSuccess() {
String str = "31-Aug-2020";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.US);
LocalDateTime localDateTime = LocalDate.parse(str, dtf).atStartOfDay();
System.out.println(localDateTime);
}
}
Output
2020-08-31T00:00
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-basic/time