问题
Date对象在网络通信中一般会被序列化为三种形式:
- 13位时间戳
- 调用toString()函数产生的形如Sat Mar 02 17:12:05 GMT+08:00的带时区信息的格式
- 自定义格式,如常见的年月日时分秒格式:yyyy-MM-dd HH:mm:ss
对于从后端发送的数据,如果使用@ResponseBody注解返回json字符串,则Spring默认将Date对象序列化为时间戳。
对于从前端发送的数据,因平台不同而异。
为统一起见,我们可固定将Date在网络通信中序列化为yyyy-MM-dd HH:mm:ss 格式。
解决
对于SpringMVC后端
在spring配置文件中加入(或修改):
<mvc:annotation-driven>
<!-- 处理responseBody 里面日期类型 -->
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat"&g