继承该类WebMvcConfigurerAdapter,注入如下bean:
@Bean
public Converter<String, Date> stringToDateConvert() {
return new Converter<String, Date>() {
@Override
public Date convert(String source) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(source);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
};
}
直接在controller中加入如下代码:
@InitBinder
public void initBinder(WebDataBinder binder){
binder.registerCustomEditor(Date.class,
new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}
自定义CustomDateSerializer类,在get属性方法上注入即可:
public class CustomDateSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws
IOException, JsonProcessingException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(value);
gen.writeString(formattedDate);
}
}
//date getter method
@JsonSerialize(using = CustomDateSerializer.class)
public Date getDate() {
return date;
}
var __dateConverter = function(param, fmt) {
if (param) {
const date = new Date(param);
if (fmt == 'yyyy-mm') {
return date.getFullYear() + '-' + (date.getMonth()+1)
} else if (fmt == 'yyyy-mm-dd hh:mm:ss') {
return date.getFullYear() + '-' + (date.getMonth()+1)+'-'+date.getDate()
+ ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
}
return date.getFullYear() + '-' + (date.getMonth()+1)+'-'+date.getDate();
}
}