SpringMvc时间非国内系统部署大坑相差8小时
😂 这篇文章最后更新于1707天前,您需要注意相关的内容是否还可用。
最近发现一个奇怪的现象,在国外Linux服务器上部署Java项目时间与国内/Windows上部署时间不一致,我用的是docker部署,因此在Linux宿主机与docker容器中时区都做了更改,但是还是有问题,存在八小时的时差,经多次尝试可以使用以下方式解决:
@ResponseBody注解默认使用jackson解析,因此我们可以配置其参数。
对于SpringBoot,在spring下面配置jackson相关属性统一处理。
spring: # 设置jackson时区 +8 一般系统时间是正确就不需要(json时间) jackson: time-zone: GMT+8 # 给返回时间格式化 date-format: yyyy-MM-dd HH:mm:ss
SpringMVC同理
<mvc:annotation-driven> <!-- 处理请求时返回json字符串的中文乱码问题 --> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8" /> </bean> <!--处理时区问题--> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="com.fasterxml.jackson.databind.ObjectMapper"> <!-- 处理responseBody 里面日期类型 --> <property name="dateFormat"> <bean class="java.text.SimpleDateFormat"> <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" /> </bean> </property> <!-- 时区指定 --> <property name="timeZone" value="GMT+8" /> <!-- 为null字段时不显示 --> <property name="serializationInclusion"> <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value> </property> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
当然也可对实体类中单独时间属性进行格式化,例如:
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date creatTime;
以上是对返回的json进行时区设置,接下来对代码中现在时间操作进行时区获取,最简单的方法:
// 注意大写HH是24小时制 小写为12小时制 static final String TIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; static final String DATE_PATTERN = "yyyy-MM-dd"; /** * 获取东8区当前时间 * @return */ public static Date getDate() { ZonedDateTime now = ZonedDateTime.now(ZoneId.of("+08:00")); String formatNow = now.format(DateTimeFormatter.ofPattern(TIME_PATTERN)); Date parse = null; try { parse = new SimpleDateFormat(TIME_PATTERN).parse(formatNow); } catch (ParseException e) { e.printStackTrace(); } return parse; } public static String getDateStr(){ ZonedDateTime now = ZonedDateTime.now(ZoneId.of("+08:00")); return now.format(DateTimeFormatter.ofPattern(DATE_PATTERN)); }
但是最后发现前端居然还是差8小时,但查看post请求接收的数据是正确的!但是前端框架我也用了js格式化日期方法对时间进行格式化!解决这个问题最简单方法使用上述的后端进行格式化时间返回给前端即可,前端不必再进行时间格式化操作。
其实也可以这样
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
需要引入依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.2</version> </dependency>
电商专用快递网站,空包网,单号网www.danhw.com