的時間和返回日期是正確的除了的小時,這比它應該是什麼少1小時。
我似乎設置是需要得到正確的時間和日期的一切:爲什麼Calendar會在正確的時區返回錯誤的小時?
- I'm using Calendar.getInstance(), instead of new Date()
- I'm setting the timezone of the Calendar instance with Timezone.getTimeZone
- I'm using DateFormat and SimpleDateFormat to format the output
我的時區是Eastern Standard Time
,又名UTC/GMT-5:00
。 無這些線都是有任何影響:
- cal.setTimeZone(TimeZone.getTimeZone(cal.getTimeZone().getDisplayName()));
- cal.setTimeZone(TimeZone.getTimeZone("EST"));
- cal.setTimeZone(TimeZone.getTimeZone("UTC"));
- cal.setTimeZone(TimeZone.getTimeZone("GMT"));
- cal.setTimeZone(TimeZone.getTimeZone("GMT-5:00"));
...但這些選項的設置我想要的時區。
這裏是我的嘗試,在那裏我錯誤地將1小時的
Calendar
實例:
PrintWriter output = null;
try {
output = new PrintWriter(
new BufferedWriter(new FileWriter("output.txt", true)));
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:ms MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
// ...doesn't seem to be working:
cal.setTimeZone(TimeZone.getTimeZone(cal.getTimeZone().getDisplayName()));
/*
* adding an extra hour here, to make up for the incorrect hour value???
* ...without this line, everything is correct except the hour = n - 1:
*/
//cal.setTimeInMillis(cal.getTimeInMillis() + (1000 * 60 * 60));
// printing to console here:
System.out.println(dateFormat.format(cal.getTime()));
System.out.println(cal.getTimeZone().getDisplayName());
// printing to the log-file here:
output.println(dateFormat.format(cal.getTime()));
output.println(cal.getTimeZone().getDisplayName());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null) {
output.close();
}
}
輸出:
10:05:43:543 10/10/2013
GMT-05:00
WRONG - 它應該是11:05:43:543
! (附註: - 我很遺憾不能使用Joda-Time)
夏令時? – John
@John - 我不知道,很好的問題......今年的夏令時期顯然從3月10日星期日開始,到11月3日星期日結束。可以'日曆'和/或'時區'*不*佔據這個? –
中有鏈接的答案: http://stackoverflow.com/questions/10545960/how-to-tackle-daylight-savings-using-timezone-in-java 希望這會有所幫助。 – guanda