前后数据交互过程中,Date类型的数据经常会出现类型映射转换的错误,为了达到业务的目标时间格式,通常会使用@JsonFormat 和 @DateTimeFormat,但是这两者有什么区别呢?

一、示例代码

先准备一个POJO,拥有Date类型的成员变量

@Data
public class DateEntity {
    private Date date;
}

在pom文件引入依赖

 <dependency>
	  <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.12</version>
 </dependency>

然后准备一个Controller,模拟前后交互

@RestController
@RequestMapping("/date")
public class DateController {

    @RequestMapping("/test")
    public DateEntity getDate(DateEntity dateEntity){
        System.out.println("入参的date:"+dateEntity.getDate());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(dateEntity.getDate());
        System.out.println("SimpleDateFormat格式化后的date:"+date);

        DateEntity result = new DateEntity();
        result.setDate(new Date());
        return result;
     }
}

然后发送一次请求

发现报错

大致意思是说String类型转换成Date类型失败,所以报了IllegalArgumentException异常;

二、使用@JsonFormat 注解

作用:

可以约束时间的接收格式和响应格式 (接收和响应的都是JSON字符串),将日期类型数据在JSON格式和java.util.Date对象之间转换。与传输方向没有关系(前端到后端or后端到前端都可以使用),注意因为我们是东八区(北京时间),使用时需要加上时区( timezone = “GMT+8”),不然所得值会比实际时间晚8小时;

名称 作用
pattern 约定时间格式:pattern=“yyyy-MM-dd HH:mm:ss”
timezone 指定具体时区: timezone = “GMT+8” or timezone = “Asia/Shanghai”

在使用@JsonFormat时需要加入@RequestBody把前台的数据以Json串的方式接收

改造controller 加入@RequestBody

    @RequestMapping("/test")
    public DateEntity getDate(@RequestBody DateEntity dateEntity){
        System.out.println("入参的date:"+dateEntity.getDate());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(dateEntity.getDate());
        System.out.println("SimpleDateFormat格式化后的date:"+date);

        DateEntity result = new DateEntity();
        result.setDate(new Date());
        return result;
    }

POJO类中加入@JsonFormat注解:

@Data
public class DateEntity {

    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    private Date date;
}

结果

三、@DateTimeFormat注解

作用

可对java.util.Date、java.uitl.calendar、java.long.Long及Joda时间类型的属性进行标注,主要处理前端时间类型与后端pojo对象中的成员变量进行数据绑定,所约束的时间格式并不会影响后端返回前端的时间类型数据格式;

注意

(注意!注意!注意!讲三遍):前端入参数据的时间格式必须与注解中定义的时间格式相同,不然会报错,如:@DateTimeFormat(pattern = “yyyy-MM-dd HH:mm”) 则入参的格式必须为"2020-6-4 10:43";

controller代码

 @RequestMapping("/test")
    public DateEntity getDate(DateEntity dateEntity){
        System.out.println("入参的date:"+dateEntity.getDate());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(dateEntity.getDate());
        System.out.println("SimpleDateFormat格式化后的date:"+date);

        DateEntity result = new DateEntity();
        Date date1 = new Date();
        result.setDate(date1);
        return result;
    }

POJO代码

@Data
public class DateEntity {

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date date;
}

测试:

结果:

四、总结@JsonFormat 和 @DateTimeFormat 区别 

@JsonFormat:

既可以约束前端传入的时间类型参数格式,也可以约束后端响应前端的时间类型格式;
@DateTimeFormat :
只能约束前端入参时间类型的格式,并不会修改原有的日期对象的格式,如果想要获得期望的日期格式,是需要自己手动转换的;
如果单独使用@DateTimeFormat 时,响应给前端的时间会比实际时间晚8个小时(时区原因)。

GitHub 加速计划 / js / json
58
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
b451735f Bumps [lukka/get-cmake](https://github.com/lukka/get-cmake) from 4.0.2 to 4.0.3. - [Release notes](https://github.com/lukka/get-cmake/releases) - [Commits](https://github.com/lukka/get-cmake/compare/ea004816823209b8d1211e47b216185caee12cc5...6b3e96a9bc9976b8b546346fdd102effedae0ca8) --- updated-dependencies: - dependency-name: lukka/get-cmake dependency-version: 4.0.3 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 2 天前
568b708f Bumps [step-security/harden-runner](https://github.com/step-security/harden-runner) from 2.12.0 to 2.12.1. - [Release notes](https://github.com/step-security/harden-runner/releases) - [Commits](https://github.com/step-security/harden-runner/compare/0634a2670c59f64b4a01f0f96f84700a4088b9f0...002fdce3c6a235733a90a27c80493a3241e56863) --- updated-dependencies: - dependency-name: step-security/harden-runner dependency-version: 2.12.1 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 7 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐