好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

jvm中指定时区信息user.timezone问题及解决方式

问题

同一份程序使用时间LocalDateTime类型,在国内和国外部署后,返回的时间信息前端使用出问题。 因为LocalDateTime不带时区信息,国内调用后,前端页面默认使用的浏览器所在os的时区(我们的系统中没有给用户设置时区), 因此会出现时间不一致, 或者判断超时了,但是实际上没有超时的问题。

解决方式:

要么返回timestamp数字类型,前端自己解析。 缺点:直接使用api的同事不方便看操作时间信息。

用户可以可以在个的profile中设置时区,方便各个时区用户在一个系统中操作。 缺点:改动较多。

最后的折中方法:
后端内部使用ZonedDateTime,返回的时间中带上时区信息。 备注:这里应用系统没有使用数据库,因为没有使用数据库时间格式。

这里遇到一个问题,国内机器都是时区为

springboot 程序启动后,ZoneDateTime 格式默认是"2023-02-16T21:44:31.914407+08:00";

但是国外的机器不行,依然不带时区信息。

在jvm启动参数中指定时区信息
国内启动不指定时间,os默认的是"Asia/Shanghai"。 国外的启动参数指定为-Duser.timezone=CET

示意:(这里是示意,省略其他参数,实际参数要跟多)
Java -jar -Dspring.profiles.active=dev -Duser.timezone=CET app.jar

具体代码

1,ObjectMapper中设置时区和时间格式

?

1

2

3

4

5

6

7

ObjectMapper mapper = new ObjectMapper();

mapper.findAndRegisterModules();

 

mapper.setTimeZone(TimeZone.getDefault()); // 在本项目必须有这样,某则有些接口中返回的ZonedDateTime序列化后不带时区信息,添加这行就会带上时区信息

mapper.registerModule( new JodaModule());

mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

return mapper;

2, 其他区地方解析返回的时间
引入依赖包

?

1

2

3

4

5

<dependency>

     <groupId>joda-time</groupId>

     <artifactId>joda-time</artifactId>

     <version>2.12.2</version>

</dependency>

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import org.joda.time.DateTime;

import org.joda.time.format.DateTimeFormat;

import org.joda.time.format.DateTimeFormatter;

 

    DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ" ).withZoneUTC();

 

     //  String str = "2022-02-16T21:44:31.914407+08:00";

     String str = "2022-02-17T14:35:48.8932+08:00" ;

 

     //String str = "2022-02-16T21:44:31+09:00";

     DateTime dateTime = formatter.parseDateTime(str);

     log.info( "dateTime:{}" , dateTime);

     String strAgain = dateTime.toString(formatter);

     log.info( "strAgain:{}" , strAgain);

到此这篇关于jvm中指定时区信息user.timezone的文章就介绍到这了,更多相关jvm时区信息user.timezone内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/russle/article/details/129094044

查看更多关于jvm中指定时区信息user.timezone问题及解决方式的详细内容...

  阅读:22次