The cause of this problem is that the operating system time zone is inconsistent with the JVM's time zone. [Email protected] ~]# TimedatectlLocal time: Thu - approx.: 44 CST universal time: thu 2016-12-29 07:35:44 UTC rtc time: thu 2016 -12-29 07:35 :45 <strong>time zone: Asia/Shanghai (CST, + 0800)</strong> NTP enabled: Yes NTP synchronized: Yes RTC in local TZ: no DST Active: n/a
You can see that the service's time zone is China time zone.
The Java program gets the GMT time (Greenwich Mean Time (0 timezone)), and the system is Shanghai time, should be gmt+8, just 8 hours. A lot of information on the Internet, there are only two ways:
1. Use Java functions in the program to set the time zone.
2. Add parameter-duser.timezone=gmt+8 When starting Java program
However, it is not always possible to modify the source code of each program to set the time zone. Nor do you want to add parameters to each Java program when it starts, too troublesome. There's no way to do it once and for all?
Starting to think that the JRE should have a configuration file that saved the time zone configuration, the result is nothing. But there's always a JRE going to the system to get the time zone configuration. So I started thinking, is Java using a system configuration file in Linux? So go to the Linux system under the/etc/sysconfig directory to see the time zone configuration. Found missing clock This file for setting the time zone. Copy this file from another Linux system and try it, OK. The time of the Java program is the same as the system time. It seems that the JRE obtains the time zone information from the/etc/sysconfig/clock file.
Attached clock file contents:
Zone= "Asia/shanghai"
Utc=false
Arc=false
zone-Time Zone
utc-indicates that the clock is set to UTC.
The arc-is used only for Alpha to indicate the use of arc.
The above is a collection of online articles, my solution is to use Java functions in the program to set the time zone.
SimpleDateFormat simpledateformat = new simpledateformat("hh:mm") ;Date d = new date(); SimpleDateFormat. Settimezone(TimeZone. getTimeZone("Asia/shanghai")); String date = simpledateformat. Format(d);
The time format I need is: hh:mm.
Java new Date () does not get the same time as the system time