版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bj_ameng/article/details/89539565
- 前台时间转后台
public class DateEditor extends PropertyEditorSupport {
public static final DateFormat DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd");
public static final DateFormat TIMEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static final DateFormat ONLY_TIMEFORMAT = new SimpleDateFormat("HH:mm:ss");
private DateFormat dateFormat;
private boolean allowEmpty = true;
/**
* Parse the Date from the given text, using the specified DateFormat.
*/
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || "".equals(text)) {
setValue(null);
} else {
try {
boolean time = text.contains(":");
boolean date = text.contains("-");
if(date && time){
setValue(TIMEFORMAT.parse(text));
}
if(date && !time){
setValue(DATEFORMAT.parse(text));
}
if(!date && time){
setValue(ONLY_TIMEFORMAT.parse(text));
}
} catch (ParseException ex) {
throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
}
}
}
/**
* Format the Date as String, using the specified DateFormat.
*/
@Override
public String getAsText() {
Date value = (Date) getValue();
DateFormat dateFormat = this.dateFormat;
if(dateFormat == null)
dateFormat = TIMEFORMAT;
return (value != null ? dateFormat.format(value) : "");
}
}
- controller中的需要增加以下,如果有baseController时,可以写到baseController中,这样就不用每个类中都写了
@InitBinder
public void initBinder(WebDataBinder binder) {
// 对于需要转换为Date类型的属性,使用DateEditor进行处理
binder.registerCustomEditor(Date.class, new DateEditor());
}
- 后端向前端返回时,需要对日期进行格式批如下:
<td th:text="${#dates.format(fleeceRecord.cashmereDate,'yyyy-MM-dd')}"></td>