2012-10-22 55 views
3

我的代碼在印度的本地服務器上運行時正確計算日期和時間,包括dayLightSaving時間。但是,當我從美國服務器運行相同的代碼時,我得到的是timeZoneId不在DST之前一小時的時間。從的LocalServer基於時區的計算時間

TimeZone tz = TimeZone.getTimeZone("America/Phoenix"); 
Date currTime = getDateByTZ(new Date(), tz); 
System.out.println("currTime" + currTime); 

public static Date getDateByTZ(Date d, TimeZone tz) throws Exception { 

    if (tz == null) { 
     tz = TimeZone.getDefault(); 
    } 
    Integer tzOffSet = tz.getRawOffset(); 
    Integer tzDST = tz.getDSTSavings(); 
    Integer defOffSet = TimeZone.getDefault().getRawOffset(); 
    Integer defDST = TimeZone.getDefault().getDSTSavings(); 
    Calendar cal = Calendar.getInstance(tz); 
    cal.setTime(d); 
    if (tz.inDaylightTime(d)) { 
     cal.add(Calendar.MILLISECOND, -defOffSet); 
     cal.add(Calendar.MILLISECOND, -defDST); 
     cal.add(Calendar.MILLISECOND, +tzOffSet); 
     cal.add(Calendar.MILLISECOND, +tzDST); 
    } else { 
     cal.add(Calendar.MILLISECOND, -defOffSet); 
     cal.add(Calendar.MILLISECOND, tzOffSet); 
    } 
    return cal.getTime(); 
} 

結果:

currTime:星期一年10月22 1點52分21秒IST 2012

結果從USserver:

currTime:星期一年10月22 02:52:21 IST 2012

+0

檢查美國和本地機器的系統時鐘,並在調整課程時間差後查看它們是否匹配。你的代碼看起來很好。 – specialscope

回答

3

此代碼沒有多大意義。日期對象不必轉換爲在其他時區使用。它代表了一個普遍的時刻。

有意義的是在顯示日期對象(或格式化爲字符串)時使用時區。在這種情況下,您應該簡單地設置DateFormat實例上的時區,並且構成日期的通用時刻將被格式化,以便對給定時區有意義。

Date now = new Date(); // now, whatever the timezone is 

DateFormat df = DateFormat.getDateTimeInstance(); 

df.setTimeZone(TimeZone.getDefault()); 
System.out.println("Now displayed in the default time zone : " + df.format(now)); 
df.setTimeZone(TimeZone.getTimeZone("America/New_York")); 
System.out.println("Now displayed in the New York time zone : " + df.format(now)); 
+0

你的意思是說代碼應該看起來像TimeZone zone = TimeZone.getTimeZone(「America/Phoenix」); DateFormat format = DateFormat.getDateTimeInstance(); format.setTimeZone(zone); System.out.println(「Date =」+ format.format(new Date()));確切地說, – user1740005

+0

。看到我編輯的答案演示代碼。 –