业务需求:把传给前端对象中的LocalDateTime 都转为时间戳。(JDK已升至8,所以全面使用LocalDateTime)
一,通过局部注解
在指定的日期格式属性字段上添加注解
入参格式化 , 该注解由Spring提供。
@DateTimeFormat(pattern= "yyyy-MM-dd HH:mm:ss")
出参格式化 ,该注解由jackson(jackson-annotations)提供,timezone要带上,不然显示的是0时区的时间
@JsonFormat( pattern= "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
然鹅,本项目项目后期才处理这个需求,所以懒得一个个去添加。而且注解太多影响阅读(个人习惯)。
二,全局配置
1.转换Date
a.Date转为时间戳
配置了Jackson,默认就会把Date转为时间戳。
b.Date转为指定格式的时间子串
在 XML中配置如下,指定对应的dateFormat 即可
<bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
</bean>
</property>
</bean>
2.转换LocalDateTime
这里记录下如何把LocalDateTime 转为 时间戳,不用每次都去搜。
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant(); long millis = instant.toEpochMil