Skip to content

@DateTimeFormat's JSR-310 formatter is not strict in case of pattern [SPR-13567] #18143

@spring-projects-issues

Description

@spring-projects-issues

Toshiaki Maki opened SPR-13567 and commented

@DateTimeFormat's formatter is not strict in case of pattern attribute specified with JSR-310 Date&Time API on JDK 8.

For example, the following Form#date will be valid even though the requested value is 2015-02-29. It will be regarded as 2015-02-28!

public class Form {
  @DateTimeFormat(pattern = "yyyy-MM-dd")
  private java.time.LocalDate date;
  // ...
}

In case of java.util.Date or org.joda.time.LocalDate, 2015-02-29 is invalid because it's checked by strict mode.

This is because DateTimeFormatterFactory produces java.time.format.DateTimeFormatter using DateTimeFormatter#ofPattern.

https://github.com/spring-projects/spring-framework/blob/master/spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeFormatterFactory.java#L176-L178

In this case, java.time.format.ResolverStyle is not STRICT but SMART.

On the other hand, when iso attribute is specified, DateTimeFormatter.ISO_XXX is used and this java.time.format.ResolverStyle is STRICT.
So @DateTimeFormat(iso = DateTimeFormatter.ISO_DATE) works fine.

I think setting ResolverStyle.STRICT is good to keep consistency of this API like following:

dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
        .withResolverStyle(ResolverStyle.STRICT);

This will be caused by the difference between Date&Time API and Joda-Time.
The following sample represents this issue plainly.

java.time.format.DateTimeFormatter dateTimeFormatter = DateTimeFormatter
        .ofPattern("yyyy-MM-dd");
System.out.println(dateTimeFormatter.parse("2015-02-29")); // valid

org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat
        .forPattern("yyyy-MM-dd");
System.out.println(formatter.parseDateTime("2015-02-29")); // invalid

Affects: 4.1.7, 4.2.1

Issue Links:

2 votes, 5 watchers

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions