I'd like to parse '2015-10-01' with LocalDateTime
. What I have to do is
LocalDate localDate = LocalDate.parse('2015-10-01');
LocalDateTime localDateTime = localDateTime.of(localDate, LocalTime.MIN);
But I'd like to parse it in one pass like
// throws DateTimeParseException
LocalDateTime date = LocalDateTime.parse('2015-10-01', DateTimeFormatter.ISO_LOCAL_DATE);
Also a small difference of a string throws the exception as well.
// throws DateTimeParseException
LocalDate localDate = LocalDate.parse("2015-9-5", DateTimeFormatter.ISO_LOCAL_DATE);
Can I parse date strings leniently with Java 8 Date APIs?
You can try
Parsing date and time
To create a
LocalDateTime
object from a string you can use the staticLocalDateTime.parse()
method. It takes a string and aDateTimeFormatter
as parameter. TheDateTimeFormatter
is used to specify the date/time pattern.Formatting date and time
To create a formatted string out a
LocalDateTime
object you can use the format() method.Note that there are some commonly used date/time formats predefined as constants in
DateTimeFormatter
. For example: UsingDateTimeFormatter.ISO_DATE_TIME
to format theLocalDateTime
instance from above would result in the string "1986-04-08T12:30:00".The
parse
() andformat
() methods are available for all date/time related objects (e.g. LocalDate or ZonedDateTime)If you want to parse date String as
"2015-10-01"
and"2015-9-5"
toLocalDateTime
objects, you can build your ownDateTimeFormatter
usingDateTimeFormatterBuilder
:The variable length of each field is handled by the call to
appendValue(field)
. Quoting the Javadoc:This means that it will be able to parse month and days formatted with 1 or 2 digits.
To construct a
LocalDateTime
, we also need to provide aLocalTime
to this builder. This is done by usingparseDefaulting(field, value)
for each field of aLocalTime
. This method takes a field and a default value for that field if it is not present in the String to parse. Since, in our case, the time information will not be present in the String, the default values will be chosen, i.e. the minimum value for the range of valid values for that field (it is obtained by callinggetMinimum
to theValueRange
of that field; perhaps we could also hard-code 0 here).In the event that the String to parse might contain time information, we can use optional sections of
DateTimeFormatter
, like this:A simple solution for your particular use case is to define your own format. In this example even though I have specified a single
M
for the month in my pattern, and a singled
for the day, it still parses both examples the same.I decided to write this answer after seeing the code soup that
DateTimeFormatterBuilder
requires you to write in order to solve the same problem.