本文共 3082 字,大约阅读时间需要 10 分钟。
项目中,leader强制要求前后端必须使用utc时间格式进行交互,也就是返回给前端的时间换成utc,同时前端调用后面时间也使用utc时间格式
总体思路就是: 1.在返回和接收时间的UtcDto实体类上加上 @JsonFormat(pattern = “yyyy-MM-dd’T’HH:mm:ss.SSS’Z’”) 2.并且在application.yml配置spring mvc接收时间的格式也为 “yyyy-MM-dd’T’HH:mm:ss.SSS’Z’”如下demo示例
只需要引入springboot web start即可
org.springframework.boot spring-boot-starter-web
完整pom文件如下:
4.0.0 org.springframework.boot spring-boot-starter-parent 2.4.1 com.cch utcdemo 0.0.1-SNAPSHOT utcdemo Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok
接收前端请求必须要有该配置,不然JsonFormat转换会失败
server: port: 8888spring: mvc: format: date: yyyy-MM-dd'T'HH:mm:ss.SSS'Z' # 接收前端请求必须要有该配置,不然JsonFormat转换会失败
其实这个只是为方便管理时间格式
public class DateUtil { public static final String UTC_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";}
在@JsonFormat 的pattern指定时间格式为UTC
package com.cch.utcdemo.dto;import com.fasterxml.jackson.annotation.JsonFormat;import lombok.Data;import java.util.Date;/** * @Author chenchanghui * @date 2021/1/14 19:37 */@Datapublic class UtcDto { @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") private Date createTime;}
@RestController@RequestMapping("/testutc")public class UtcController { /** * 后端返回utc时间给前端 * @return */ @RequestMapping(value = "", method = RequestMethod.GET) public ResponseEntity getUtcDate() { UtcDto utcDto = new UtcDto(); utcDto.setCreateTime(new Date()); return new ResponseEntity(utcDto, HttpStatus.OK); } /** * 后端接收前端发送的utc时间 * @param utcDto */ @RequestMapping(value = "/query", method = RequestMethod.GET) public void queryUtcDate(UtcDto utcDto) { System.out.println(utcDto.getCreateTime()); }}
后端返回前端UTC时间格式,测试ok
前端发送UTC时间格式给后端,测试ok
工作中,后端返回utc时间给前端,前端根据浏览器所在时区进行处理展示。
同时前端发送请求给后端的时间也根据浏览器所在时区进行转换才发送给后端。转载地址:http://mkrii.baihongyu.com/