SSM日期类型的转换

SSM日期类型的转换:

数据库中的日期格式是datetime,但是后台读取日期的时候, 得到的却是时间戳.针对这个情况,我们可以使用@JsonFormat来解决这个问题.


@JsonFormat的使用(后端从数据库中获取时间给前段显示)

我们可以在对象的属性或者是getter方法上进行注解:

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date releasedate;

上面注解中pattern是你需要转换的日期的格式,
timezone是东八区时间

需要导入的包:

import com.fasterxml.jackson.annotation.JsonFormat;

pom.xml

2.4.2
   
   
      com.fasterxml.jackson.core
      jackson-databind
      ${jackson.version}
   


在springmvc.xml中使用注解器

    
    
    

日期可以在前台正常显示了:

 

@DateTimeFormat的使用(后端从前端获取时间往数据库中存储)

我们不仅要从后台从数据库读取数据到前台,还需要 把前台数据通过后台存储到数据库中.所以需要另外一个注解那就是@DateTimeFormat.
同样的在属性上使用注解:

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date releasedate;

需要导入的包:

import org.springframework.format.annotation.DateTimeFormat;

这是我有关spring的pom.xml文件:

3.2.0.RELEASE

   
      org.springframework
      spring-context
      ${spring.version}
   

   
      org.springframework
      spring-beans
      ${spring.version}
   

   
      org.springframework
      spring-beans
      ${spring.version}
   

   
      org.springframework
      spring-test
      ${spring.version}
   

   
      org.springframework
      spring-jdbc
      ${spring.version}
   

   
      org.springframework
      spring-aspects
      ${spring.version}
   

   
      org.springframework
      spring-jms
      ${spring.version}
   

   
      org.springframework
      spring-web
      ${spring.version}
   

   
      org.springframework
      spring-aop
      ${spring.version}
   

   
      org.springframework
      spring-tx
      ${spring.version}
   

   
      org.springframework
      spring-webmvc
      ${spring.version}
   

   
      org.springframework
      spring-context-support
      ${spring.version}
   


参考博客:
[1]@JsonFormat与@DateTimeFormat注解的使用
[2]Jackson 时间格式化,时间注解 @JsonFormat 用法、时差问题说明
[3]SSM日期类型的转化

你可能感兴趣的:(SSM)