1

I have a class like this. I want to enforce that the two Date fields should take in the request only if the date in request comes in a valid ISO Date time format like: 2021-01-19T12:20:35+00:00

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Validated
public class EDDDetail {

  @NotBlank
  private String versionId;

  @NotNull
  private Date minTime;

  @NotNull
  private Date maxTime;
}

How to achieve this? Currently this accepts a date in long format (epoch time [e.g.: 1611058835000] ) and other valid dates as well like 22-02-2021 etc. I want to throw a bad request if the date format in the request is not an ISO format date.

G V Sandeep
  • 226
  • 1
  • 4
  • 14

2 Answers2

1

You can use @JsonFormat annotation with provided pattern to format the date

E.g:

@JsonFormat(pattern = "yyyy-MM-dd")
Hưng Chu
  • 1,027
  • 5
  • 11
1

You can use the @JsonFormat annotation to define your pattern:

  @NotNull
  @JsonFormat(pattern="dd-MM-yyyy")
  private Date minTime;

  @NotNull
  @JsonFormat(pattern="dd-MM-yyyy")
  private Date maxTime;

If you want to accept multiple patterns you can get some implementation on this link: Configure Jackson to parse multiple date formats

Patrick
  • 12,336
  • 15
  • 73
  • 115