博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springboot 返回前端utc时间格式和接收前端提交utc时间
阅读量:4100 次
发布时间:2019-05-25

本文共 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示例

一、项目结构

在这里插入图片描述

二、pom依赖

只需要引入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

三、application.yml配置如下

接收前端请求必须要有该配置,不然JsonFormat转换会失败

server:  port: 8888spring:  mvc:    format:      date: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'  # 接收前端请求必须要有该配置,不然JsonFormat转换会失败

四、DateUtil

其实这个只是为方便管理时间格式

public class DateUtil {
public static final String UTC_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";}

五、UtcDto

在@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;}

六、UtcController

@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/

你可能感兴趣的文章
hbase(1)---概述
查看>>
hbase(5)---API示例
查看>>
SSM-CRUD(1)---环境搭建
查看>>
SSM-CRUD(2)---查询
查看>>
SSM-CRUD (3)---查询功能改造
查看>>
Nginx(2)---安装与启动
查看>>
springBoot(5)---整合servlet、Filter、Listener
查看>>
C++ 模板类型参数
查看>>
C++ 非类型模版参数
查看>>
DirectX11 光照
查看>>
图形学 图形渲染管线
查看>>
DirectX11 计时和动画
查看>>
DirectX11 光照与材质的相互作用
查看>>
DirectX11 环境光
查看>>
DirectX11 镜面光
查看>>
DirectX11 三种光照组成对比
查看>>
DirectX11 指定材质
查看>>
DirectX11 平行光
查看>>
DirectX11 点光
查看>>
DirectX11 聚光灯
查看>>