G V Sandeep
G V Sandeep

Reputation: 233

How to enforce DateTime format in Spring Boot API Request?

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.

Upvotes: 1

Views: 1195

Answers (2)

Patrick
Patrick

Reputation: 12734

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

Upvotes: 1

Hưng Chu
Hưng Chu

Reputation: 1052

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

E.g:

@JsonFormat(pattern = "yyyy-MM-dd")

Upvotes: 1

Related Questions