前言
在我们日常开发中经常会发现后台获取的日期格式在前台显示的都是一串时间戳(比如 1280977330000),或者前台发送到后台出现400接收错误,这有时候也是时间接收的问题(当然也可能不是)。这里提供两种方式解决问题。
后台传前台
只需要加入注解@JsonFormat
@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
private Date time;
前台传入后台时候
我通常使用的是消息转换器,自定义一个类注入到spring中。当然还有简单的方式:在实体字段上面加@DateTimeFormat(pattern=”yyyy-MM-dd HH:mm:ss”) 【这个是可以喝上面的注解一块儿使用的】
spring.xml加入配置
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.tellhow.social.controller.CustomDateConverter"/>
</list>
</property>
</bean>
CustomDateConverter.java
package com.tellhow.social.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
/**
* 时间格式转换器--在配置文件里面使用到
* @author Administrator
*
*/
public class CustomDateConverter implements Converter<String,Date>{
public Date convert(String source) {
//实现 将日期串转成日期类型(格式是yyyy-MM-dd HH:mm:ss)
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
//转成直接返回
return simpleDateFormat.parse(source);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//如果参数绑定失败返回null
return null;
}
}
以上两个方法就能让时间字段前后台都是正常显示的了