srping mvc 日期类型 注入Date 解决--@DatetimeFormat

一、时间格式注入

因为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

jackson有个注解@JsonSerialize可以放在geter上
@Column(name = "BIRTHDAY", length = 10)
@JsonSerialize(using = CustomDateSerializer.class)
public Date getBirthday() {
return this.birthday;
}
@DateTimeFormat(pattern="yyyy-MM-dd")
public void setBirthday(Date birthday) {
this.birthday = birthday;
}

自定义转化类:

转化为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()));

}

 

 

}

你可能感兴趣的:(@DateTimeFormat)