问题
String s = "2020 Jun 31";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MMM dd");
LocalDate date = LocalDate.parse(s, formatter);
System.out.println(date);
Output:
2020-06-30
Why does 31 turn into 30 without any warnings or exceptions?
回答1:
DateTimeFormatter has a ResolverStyle that affects how strict or lenient the parser should be with invalid date and time values. To get an exception in this case you need to set the resolver style to STRICT.
You also need to use u
(year) instead of y
(year-of-era) in the format string.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu MMM dd")
.withResolverStyle(ResolverStyle.STRICT);
The default resolver type is SMART
:
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.
回答2:
The ResolverStyle
is an enum that offers three different approaches: strict, smart and lenient. The smart option is the default. It can be set using withResolverStyle(ResolverStyle)
. The following code will throw an exception:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String s = "2020 Jun 31";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("u MMM d")
.withResolverStyle(ResolverStyle.STRICT)
.localizedBy(Locale.ENGLISH);
LocalDate date = LocalDate.parse(s, formatter);
System.out.println(date);
}
}
However, it will work without any exception for the day as 30
i.e. the output will be 2020-06-30
for String s = "2020 Jun 30"
.
Check Resolving section at https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html for more details.
来源:https://stackoverflow.com/questions/63315211/does-localdate-parse-silently-correct-day-number