一、时间格式注入
因为springMVC没有提供默认的日期转换器,前段页面传递过来日期字符串怎么转换为日期类型,如果没有提供全局日期转换器或者数据绑定的基础上,可以使用@DatetimeFormat注解完成
放在seter上
@Column(name = "BIRTHDAY", length = 10)
public Date getBirthday() {
return this.birthday;
}
@DateTimeFormat(pattern="yyyy-MM-dd")
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
二、时间格式 输出返回json
spring mvc 默认输出json是用jackson
自定义转化类:
转化为yyy-MM-dd
public class CustomDateSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String str = sdf.format(value);
jgen.writeString(str);
}
}
转化为yyyy-MM-dd HH:mm:ss"
public class CustomDateTimeSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf.format(value);
jgen.writeString(str);
}
}
转化为毫秒数
public class CustomTimestampSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeString(String.valueOf(value.getTime()));
}
}