With Java 8's new date time library, the way to parse strings into dates is to use the DateTimeFormatter
. LocalDate
, LocalTime
and LocalDateTime
all have a static parse method that takes in a String and a formatter. A potential gotcha is that if your DateTimeFormat does not contain a time portion (or for DateTime, a date portion) you end up getting a parse error even if your pattern matches.
Example
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-DD");
LocalDateTime dt = LocalDateTime.parse("2016-01-11", formatter);
This will throw a DateTimeParseException
(as discussed here) with the message
java.time.format.DateTimeParseException:
Text '2016-01-11' could not be parsed:
Unable to obtain LocalDateTime from TemporalAccessor
This is a somewhat unhelpful error message as the text can be parsed since it matches the pattern. Rather the error has to do with the fact that it cannot create the time portion of LocalDateTime. Refactoring the code to the below works:
LocalDateTime ldt = LocalDate.parse("2016-01-11", formatter).atStartOfDay());
My question is, say you had a generic method like such
public static LocalDateTime getDate(String s, DateTimeFormatter format) {
...
}
Is there a way to determine which static parse method you would need to call to coerce the string into a LocalDateTime by applying some default logic? e.g. If date only use midnight, if time only use today, etc.