今天发现刚写的Java小工具的日期功能出了问题。具体时间慢了11个小时。
检查了XP系统的日期、时区以及注册表中的相关选项,均无问题。
运行下列代码
import java.util.TimeZone;
import java.util.Calendar;
public class Test{
public static void main(String[] args) throws Exception {
Calendar calendar = Calendar.getInstance();
System.out.println("目前时间:" + calendar.getTime());
System.out.println("Calendar时区::" + calendar.getTimeZone().getID());
System.out.println("user.timezone:" + System.getProperty("user.timezone"));
System.out.println("user.country:" + System.getProperty("user.country"));
System.out.println("默认时区:" + TimeZone.getDefault().getID());
}
}
输出为:
-----------Output-----------
目前时间:Thu Jan 22 04:50:19 BRT 2015
Calendar时区::America/Bahia
user.timezone:America/Bahia
user.country:CN
默认时区:America/Bahia
现在是15:50,足慢了11小时,时区居然是美国,但是国家却是中国。
用以获取Calendar实例后,使用setTimeZone()方法,把时区设为东八区,再次运行输出如下:
-----------Output-----------
目前时间:Thu Jan 22 04:52:58 BRT 2015
Calendar时区::Asia/Shanghai
user.timezone:America/Bahia
user.country:CN
默认时区:America/Bahia
虽然Calendar中的时区虽然改成了东八区,但还是显示美国时间,国家依然在中国。
看来输出的时间跟默认时区相关。
删掉Calendar的setTimeZone()方法,修改TimeZone类中的默认时区:
import java.util.TimeZone;
import java.util.Calendar;
public class Test{
public static void main(String[] args) throws Exception {
System.setProperty("user.timezone","Asia/Shanghai");
// 用下面的方法也可以,但是它并不会设置user.timezone属性。建议用上面的方法
// TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
Calendar calendar = Calendar.getInstance();
System.out.println("目前时间:" + calendar.getTime());
System.out.println("Calendar时区::" + calendar.getTimeZone().getID());
System.out.println("user.timezone:" + System.getProperty("user.timezone"));
System.out.println("user.country:" + System.getProperty("user.country"));
System.out.println("默认时区:" + TimeZone.getDefault().getID());
}
}
这时输出:
-----------Output-----------
目前时间:Thu Jan 22 16:06:17 CST 2015
Calendar时区::Asia/Shanghai
user.timezone:Asia/Shanghai
user.country:CN
默认时区:Asia/Shanghai
谢天谢地,总算正常了。
问题的原因出在哪里?为什么我的Java默认时区是美国?Google之后发现许多人都遇到过这个Bug,一般都是由于JDK版本落后或者系统注册表中的时区有误造成的。但是我的系统设置并无问题,JDK版本是最新的1.8,难道是XP与JDK1.8之间有不合?
具体的TimeZone机制可以看这篇文章:
http://log-cd.iteye.com/blog/368238
版权声明:本文为博主原创文章,未经博主允许不得转载。