I am trying to parse this data "Aug 29, 2023 5:48:51 PM" which is in String format to JSON but getting the below error
Can not deserialize value of type java.util.Date from String "Aug 29, 2023 5:48:51 PM": expected format "yyyy-MM-dd HH:mm:ss.SSS"
The POJO declaration of the corresponding field is given below:
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss.SSS")
@Column(name = "createdOn")
private Date createdOn;
Pls help
I have tried to modify the pojo declaration of the field to this
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss.SSS")
@Column(name = "createdOn")
private Date createdOn;
The java.util
date-time API and their corresponding parsing/formatting type, SimpleDateFormat
are outdated and error-prone. In March 2014, the modern Date-Time API supplanted the legacy date-time API. Since then, it has been strongly recommended to switch to java.time
, the modern date-time API.
The format corresponding to your date-time string is MMM dd, uuuu h:m:s a
in the en_US
locale.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String[] args) {
DateTimeFormatter parser = DateTimeFormatter.ofPattern("MMM dd, uuuu h:m:s a", new Locale("en_US"));
System.out.println(LocalDateTime.parse("Aug 29, 2023 5:48:51 PM", parser));
}
}
Output:
2023-08-29T17:48:51
Based on this description, you can make the following changes in your code:
@JsonFormat(pattern = "MMM dd, uuuu h:m:s a", shape = JsonFormat.Shape.STRING, locale = "en_US")
@Column(name = "createdOn")
private LocalDateTime createdOn;
Learn about the modern date-time API from Trail: Date Time