今天發現剛寫的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 2015Calendar時區::America/Bahiauser.timezone:America/Bahiauser.country:CN預設時區:America/Bahia
現在是15:50,足慢了11小時,時區居然是美國,但是國家卻是中國。
用以擷取Calendar執行個體後,使用setTimeZone()方法,把時區設為東八區,再次運行輸出如下:
-----------Output----------- 目前時間:Thu Jan 22 04:52:58 BRT 2015Calendar時區::Asia/Shanghaiuser.timezone:America/Bahiauser.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 2015Calendar時區::Asia/Shanghaiuser.timezone:Asia/Shanghaiuser.country:CN預設時區:Asia/Shanghai
謝天謝地,總算正常了。
問題的原因出在哪裡。為什麼我的Java預設時區是美國。Google之後發現許多人都遇到過這個Bug,一般都是由於JDK版本落後或者系統註冊表中的時區有誤造成的。但是我的系統設定並無問題,JDK版本是最新的1.8,難道是XP與JDK1.8之間有不合。
具體的TimeZone機制可以看這篇文章:
http://log-cd.iteye.com/blog/368238