'uuuu' versus 'yyyy' in DatetimeFormatter in java
Learn to parse date and time strings into instances of LocalDate
and LocalDateTime
using strict style using ResolverStyle.STRICT
parameter with DateTimeFormatter instance.
ResolverStyle – Parsing styles
Parsing a string to date in Java happens in two phases:
ResolverStyle
is anenum
and used to control how phase 2, resolving, happens. It contains three styles of parsing:
STRICT
public static final ResolverStyle STRICTStyle to resolve dates and times strictly.
Using strict resolution will ensure that all parsed values are within the outer range of valid values for the field. Individual fields may be further processed for strictness.
For example, resolving year-month and day-of-month in the ISO calendar system using strict mode will ensure that the day-of-month is valid for the year-month, rejecting invalid values.
//Example of yyyy
fun main() {
println(DateTimeFormatter.ofPattern("dd/MM/yyyy").withResolverStyle(ResolverStyle.STRICT).parse("31/02/2023"));
}
//Example of uuuu with ResolverStyle property
fun main() {
println(DateTimeFormatter.ofPattern("dd/MM/uuuu").withResolverStyle(ResolverStyle.STRICT).parse("31/02/2023"));
}
// Format using 'uuuu'
fun main() {
println(DateTimeFormatter.ofPattern("dd/MM/uuuu").parse("31/02/2023"));
}