Java前后端时间格式的转化方式

 更新时间:2021年8月11日 08:00  点击:1994

JsonFormat、DateTimeFormat使用

从数据库获取时间传到前端进行展示的时候,我们有时候可能无法得到一个满意的时间格式的时间日期,在数据库中显示的是正确的时间格式,获取出来却变成了很丑的时间戳,@JsonFormat注解很好的解决了这个问题,我们通过使用@JsonFormat可以很好的解决:后台到前台时间格式保持一致的问题。

其次,另一个问题是,我们在使用WEB服务的时,可能会需要用到,传入时间给后台,比如注册新用户需要填入出生日期等,这个时候前台传递给后台的时间格式同样是不一致的,而我们的与之对应的便有了另一个注解,@DataTimeFormat便很好的解决了这个问题,接下来记录一下具体的@JsonFormat与DateTimeFormat的使用过程。

@JsonFormat

导入依赖

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>

在你需要查询出来的时间的数据库字段对应的实体类的属性上添加 @JsonFormat

@Data
@Api("升级日志返回值")
public class UpgradeLogRes {
    @ApiModelProperty("升级日志id")
    private Long id;
    @ApiModelProperty("版本名称")
    private String name;
    @ApiModelProperty("发布日期")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date postDate;
    @ApiModelProperty("内容日志")
    private String contentLog;
    @ApiModelProperty("发布状态")
    private Integer postStatus;
    @ApiModelProperty("内容日志Url")
    private String contentLogUrl;
}

注:@JsonFormat(pattern=“yyyy-MM-dd”,timezone = “GMT+8”)

pattern:是你需要转换的时间日期的格式

timezone:是时间设置为东八区,避免时间在转换中有误差

提示:@JsonFormat注解可以在属性的上方,同样可以在属性对应的get方法上,两种方式没有区别

@DateTimeFormat

导入依赖:@DateTimeFormat的使用和@jsonFormat差不多,首先需要引入是spring还有jodatime,spring我就不贴了

    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.3</version>
    </dependency>

在controller层我们使用spring mvc 表单自动封装映射对象时,我们在对应的接收前台数据的对象的属性上加@DateTimeFormat

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

我这里就只贴这两个属性了,这里我两个注解都同时使用了,因为我既需要取数据到前台,也需要前台数据传到后台,都需要进行时间格式的转换,可以同时使用

总结一下:

  • 注解@JsonFormat主要是后台到前台的时间格式的转换
  • 注解@DataFormAT主要是前后到后台的时间格式的转换

java前后端Date接收

1.前端传Date对象

将其转为“yyyy-MM-dd HH:mm:ss”的字符串,后台用@DateTimeFormat(pattern=“yyyy-MM-dd HH:mm:ss”)格式化Date属性

2.后台返回给前端Date

传的是时间戳,用@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”, timezone = “GMT+8”)对其格式化,

timezone是用于调整时区的属性(东八区),不加的话得到的时间会比实际的少8个小时

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

3.时间比较:

mybaties :

startTime, endTime是经过@DateTimeFormat格式后的Date对象

 <if test="startTime != null">
       and alarm.createTime &gt;= #{startTime}
</if>
<if test="endTime != null">
       and alarm.createTime &lt;= #{endTime}
</if>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。

[!--infotagslink--]

相关文章