Reputation: 1214
Why can I parse a date time string in java with an invalid hour? What have I missed or need to do to ensure that it throws an error appropriately.
The following code does not throw an error, where it should?
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss");
LocalDateTime aFormattedDate = LocalDateTime.parse("2019-01-01T24:00:00", dateTimeFormatter); // returns 2019-01-02T00:00:00, should throw an error
Specifying the hour as 25, or including any millisecond or other time component does cause parse
to throw an error.
Where as
LocalDateTime aDate = LocalDateTime.parse("2019-01-01T24:00:00"); //throws an error
Does throw an error - about HourOfDay needs to be between 0 and 23 - as expected
Upvotes: 4
Views: 700
Reputation: 44952
ResolverStyle
Because DateTimeFormatter.ofPattern()
defaults to ResolverStyle.SMART
if the resolver style is not specified. SMART
allows for some conversionse.g. 24:00:00
will be converted to the next day but 24:00:01
will throw an exception. As per the enum javadoc:
Style to resolve dates and times in a smart, or intelligent, manner.
Using smart resolution will perform the sensible default for each field, which may be the same as strict, the same as lenient, or a third behavior. Individual fields will interpret this differently.
For example, resolving year-month and day-of-month in the ISO calendar system using smart mode will ensure that the day-of-month is from 1 to 31, converting any value beyond the last valid day-of-month to be the last valid day-of-month.
LocalDateTime.parse()
uses ResolveStyle.STRICT
under the hood which makes it equivalent to:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss")
.withResolverStyle(ResolverStyle.STRICT);
LocalDateTime.parse("2019-01-01T24:00:00", fmt); // DateTimeParseException
Upvotes: 4