0

how can I parse date to 'dd-MMM-yyyy' format using @JsonFormat from Jackson library? I am using Java 8 and Jackson 2.8.9.

Example: I would like to get: 2019-06-22T00:00:00Z -> 22-Jun-2019

I am using

@JsonFormat(pattern = "dd-MMM-yyy")
private Date myDate;

and I receive an exception:

JSON parse error: Can not deserialize value of type java.util.Date from String "2019-06-22T00:00:Z": expected format "dd-MMM-yyyy"

I thought I would be able to parse that date to expected format, but it looks like it is impossible in that way. Do you have any suggestions how can I do it? Im looking for the best approach. Can I do it using this annotation?

  • are you on java 8+ version? – Govinda Sakhare Jul 06 '20 at 13:47
  • You have one format in your question, another in your code sample and none of them match the input String. If you have the date in a String to start with you must parse the incoming String first. Once you have it represented in an object you can format the output the way you want. But I am not sure that is what you are trying to achieve. – DanielBarbarian Jul 06 '20 at 13:48
  • @Govi S: I am on Java 8 –  Jul 06 '20 at 14:03
  • @DanielBarbarian: Sorry. It was a mistake in my code, now it's good format. This myDate variable is part of a model, I am looking for a way to do an instant parsing without additional methods or objects. –  Jul 06 '20 at 14:03
  • By the way, I suggest you educate the publisher of your data about the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) standard formats to use when exchanging date-time values as text. – Basil Bourque Jul 06 '20 at 14:31

2 Answers2

1

As you are on java 8, you should use LocalDate and not the old API.

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MMM-yyyy")
private final LocalDate localDate;

I was able to de-serialize with Date API also. If it doesn't work, try updating jackson artifact.

Govinda Sakhare
  • 5,009
  • 6
  • 33
  • 74
  • I did it the same like you did, but I've got an exception: _java.time.format.DateTimeParseException: Text '2019-06-22T00:00:00Z' could not be parsed at index 2_ - I added dependency _jackson-datatype-jsr310_ and created ObjectMapper Bean with JavaTimeModule(). –  Jul 06 '20 at 16:40
  • Try updating Jackson. – Govinda Sakhare Jul 07 '20 at 03:27
0

use this library dateFormat

 dateFormat('your date variable', "mm/dd/yyyy")

always does the trick

Pavan Kalyan
  • 377
  • 1
  • 10