Is there any way to make Spring decodes both string (es. yyyy-mm-dd HH:MM:ss) and long (unixtime milliseconds) for Date objects?
1 Answer
You can register a custom Converter that tries both Unix timestamps and formatted strings. Simple example:
@Component
public class Converter implements Converter<String, Date> {
private static final String[] FORMATS = {
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd'T'HH:mm:ss",
"yyyy-MM-dd"...etc
};
@Override
public Date convert(String source) {
return new Date(Long.parseLong(source));
for (String f : FORMATS) {
return new SimpleDateFormat(f).parse(source);
}
}
}
Spring Boot will automatically pick this up for @RequestParam, @PathVariable, and @RequestBody bindings.
For LocalDateTime, just implement Converter<String, LocalDateTime> and use DateTimeFormatter / Instant.ofEpochMilli(). If you decide to use this snippet, make sure to use some try catches is my recommendation.
2 Comments
M. Deinum
This will not work with
@RequestBody as that doesn't use a converter but Jackson (by default unless a different library is added and used). It will only work for request parameters, path variables and if you are luckily for header values.Tobia
Ok thanks, how can I let it work with requestbody?