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?

5
  • are you on java 8+ version? Commented Jul 6, 2020 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. Commented Jul 6, 2020 at 13:48
  • @Govi S: I am on Java 8 Commented Jul 6, 2020 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. Commented Jul 6, 2020 at 14:03
  • By the way, I suggest you educate the publisher of your data about the ISO 8601 standard formats to use when exchanging date-time values as text. Commented Jul 6, 2020 at 14:31

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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().
Try updating Jackson.
0

use this library dateFormat

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

always does the trick

Comments

0

In java 8 and above you can use as follows:

 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
private LocalDate month;

1 Comment

Repeating what Govinda Sakhare already said (a good idea, though).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.