Answer the question
In order to leave comments, you need to log in
How to convert a unix timestamp string to a Date object in a Spring boot controller?
There is a controller:
@RequestMapping(value = "/add/**", method = RequestMethod.POST)
public @ResponseBody Response<Post> addPost(PostDTO postDTO) {
...
}
and DTOs:public class PostDTO {
private Date date;
...
}
When I try to pass the date=1456154872983 parameter via POST, I get the following error:Could not parse date: Unparseable date: \"1456154872983\"","objectName":"postDTO","field":"date"
I figured out how to set up custom format conversion through InitBinder, everything worked out with it, but I just can’t find how to work with a regular unix timestamp. Answer the question
In order to leave comments, you need to log in
Understood. It is enough to override the PropertyEditorSupport class and register it. In the setAsText method, where the string with the date comes in, you can already process it in any way you like.
I'm posting the solution in case anyone needs it.
In the controller, you need to add a method in which the editor is registered:
@InitBinder
public final void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new UnixTimestampDateEditor(true));
}
import org.springframework.util.StringUtils;
import java.beans.PropertyEditorSupport;
import java.util.Date;
public class UnixTimestampDateEditor extends PropertyEditorSupport {
private boolean allowEmpty;
public UnixTimestampDateEditor(boolean allowEmpty) {
this.allowEmpty = allowEmpty;
}
public UnixTimestampDateEditor(boolean allowEmpty, Object source) {
super(source);
this.allowEmpty = allowEmpty;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
try {
if (this.allowEmpty && !StringUtils.hasText(text)) {
setValue(null);
} else {
long unixTimestamp = Long.parseLong(text);
if (unixTimestamp < 0) {
throw new IllegalArgumentException("argument < 0 ");
}
Date date = new Date(unixTimestamp * 1000);
setValue(date);
}
} catch (NumberFormatException pe) {
throw new IllegalArgumentException("Could not parse date: " + pe.getMessage(), pe);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question