Spring中@JsonFormat与@DateTimeFormat注解使用简介说明

转自:

Spring中@JsonFormat与@DateTimeFormat注解使用简介说明

下文笔者讲述Spring中JsonFormat和DateTimeFormat注解的简介说明,如下所示

JsonFormat和DateTimeFormat配置方式

spring boot在application.yml,给出默认的格式
spring:
  mvc:
    date-format: yyyy-MM-dd HH:mm:ss
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

注解方式

由于对前端传送过来的参数格式有一定的要求
 所以我们需提前和后端进行一些特殊数据格式的约定
 那么如何约定呢?
   例:我们可以使用JsonFormat和DateTimeFormat注解对数据进行定义 
  
  注解@JsonFormat:后台到前台的时间格式的转换
  注解@DateTimeFormat:前后到后台的时间格式的转换

注解@JsonFormat

pom.xml引入依赖
<!--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>

实体或VO添加注解

@ApiModelProperty("加入时间")
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd")
private Date entryTime;
@JsonFormat(timezone = "GMT+8",pattern="yyyy-MM-dd")

timezone:时区,设置为东八区,避免时间在转换中有误差
pattern:要转换成的时间格式
说明:@JsonFormat注解,可以置于属性上方,也可以置于属性对应get方法上方。

注解@DateTimeFormat

 
<!-- joda-time -->
<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 entryTime;
 
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date formlTime;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值