Java程序时区错误
1、问题现象
用命令查看服务器显示:
# date +"%Z %::z"
CST +08:00:00
使用 jinfo
查看Java程序使用的时区:
# jinfo 16846 | grep user.timezone
user.timezone = America/New_York
2、原因分析
首先我们来看下Java程序是怎样取得时区信息的。通过Oracle的官方文档,我们可以知道其默认时区的获取方式:
- Use the user.timezone property value as the default time zone ID if it’s available.
- Detect the platform time zone ID. The source of the platform time zone and ID mapping may vary with implementation.
- Use GMT as the last resort if the given or detected time zone ID is unknown.
我们通过date命令看到的CST有什么区别和联系呢? 查阅资料发现,Linux和Java都是通过IANA提供的时区数据库获取时区信息的。我们得到的CST,称为时区简写名称,并且与时区名称是一对多的关系。一个CST可能会对应多个时区名称:
Abbreviation | Time zone name | Location | Offset |
---|---|---|---|
CST | Central Standard Time | North America | UTC -6 |
CST | CT - Central Time | Central America | |
CST | NACST - North American Central Standard Time | ||
CST | CST - Tiempo Central Estándar (Spanish) | ||
CST | HNC - Heure Normale du Centre (French) | ||
CST | China Standard Time | Asia | UTC +8 |
CST | Cuba Standard Time | Caribbean | UTC -5 |
查看系统具体时区:
# ls -li /etc/localtime
74 lrwxrwxrwx. 1 root root 38 Oct 10 2019 /etc/localtime -> ../usr/share/zoneinfo/America/New_York
通过保存在Linux系统中的时区数据库(/usr/share/zoneinfo/ 目录内)证实:
# zdump PRC America/New_York Asia/Shanghai
PRC Thu Nov 26 18:46:35 2020 CST
America/New_York Thu Nov 26 18:46:35 2020 CST
Asia/Shanghai Thu Nov 26 18:46:35 2020 CST
# ls -li /usr/share/zoneinfo/{PRC,America/New_York,Asia/Shanghai}
12673 -rw-r--r--. 3 root root 528 Apr 22 2020 /usr/share/zoneinfo/America/New_York
12677 -rw-r--r--. 5 root root 528 Sep 26 2019 /usr/share/zoneinfo/Asia/Shanghai
12677 -rw-r--r--. 5 root root 528 Sep 26 2019 /usr/share/zoneinfo/PRC
事实表明确实是由于系统时区错误导致Java程序中时区与系统相同
3、解决方案
(1)启动Java项目时设置jvm时区
java -Duser.timezone=Asia/Shanghai
(2)启动Java项目是设置环境变量TZ
比如TZ=Asia/Shanghai
(3)修改系统 /etc/localtime
# timedatectl list-timezones |grep Shanghai #查找中国时区的完整名称
Asia/Shanghai
# timedatectl set-timezone Asia/Shanghai #其他时区以此类推
或者直接手动创建软链接
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
参考资料:https://blog.csdn.net/weixin\_33736649/article/details/91964164
还没有评论,来说两句吧...