Resolving Date Parsing Exceptions in Spring Boot REST Endpoints
Reproducing the Error
Domain Model
import lombok.Data;
import java.util.Date;
@Data
public class UserProfile {
private String username;
private String location;
private Date createdAt;
}
Endpoint Definition
@PostMapping("/dates/submit")
@ResponseBody
public String processDate(UserProfile profile) {
return profile.getCreatedAt().toString();
}
Scenairo 1: Query Parameter Submission
When the client transmits the date as a URL query string (e.g., ?createdAt=2024-02-09 22:22:33), the server throws a conversion exception.
ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2024-02-09 22:22:33'; nested exception is java.lang.IllegalArgumentException
Scenario 2: Multipart Form Data Submission
Submitting the value via form-data (e.g., createdAt=2024-02-07) results in the exact same conversion failure.
ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2024-02-07'; nested exception is java.lang.IllegalArgumentException
Scenario 3: JSON Payload Submission
To accept JSON, the @RequestBody annotation must be added to the controller method:
@PostMapping("/dates/submit")
@ResponseBody
public String processDate(@RequestBody UserProfile profile) {
return profile.getCreatedAt().toString();
}
Using a simple date pattern (yyyy-MM-dd) like "2024-06-08" in the JSON body deserializes sucessfully. However, sending a timestamp with time components (yyyy-MM-dd HH:mm:ss), such as "2024-06-08 22:11:33", triggers a Jackson parsing error.
HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2024-06-08 22:11:33": not a valid representation (error: Failed to parse Date value '2024-06-08 22:11:33': Cannot parse date "2024-06-08 22:11:33": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null))