JavaScript
- 1 ответ
- 0 вопросов
1
Вклад в тег
@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);
}
}
}