0

I have an angular app which send me a date like this dd/MM/yyyy and like this yyyy-MM-dd. How can i use @JsonFormat to accept two kind of pattern? Currently i just use:

@Temporal(TemporalType.DATE)
@JsonFormat(pattern="dd/MM/yyyy")
private Date hireDate;

it's work when the date that i receive is in this format dd/MM/yyyyy but when the date is in this format yyyy-MM-dd i have a json parse error

 org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2018-10-26": expected format "dd/MM/yyyy";
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
Syllaba Abou Ndiaye
  • 213
  • 1
  • 7
  • 21

1 Answers1

1

The json format accepts a single argument. You can use regex instead or a custom deserializer.

Pattern:

@Temporal(TemporalType.DATE)
@JsonFormat(pattern="^(\\d{2}/\\d{2}/\\d{4})|^(\\d{4}-\\d{2}-\\d{2})"
private Date hireDate;

Custom deserializer:(https://stackoverflow.com/a/5598277)

@JsonDeserialize(using = CustomJsonDateDeserializer.class)

P.S: Please note that the regex pattern I gave doesn't cover the date validation of wrong months or wrong number of days. Thus I advice to use custom deserializer or ask the caller to send in UTC timestamp format.

Karthik R
  • 5,523
  • 2
  • 18
  • 30