昨天我有一個同樣的問題。我住在CET時區(中歐時間),簡單地創建DateTime
小區的時間大約一個小時。
起初,我試圖在官方教程建議設置時區上GMT
。
final DateFormat valueFormatDate = new DateFormat("dd.MM.yyyy HH:mm");
valueFormatDate.getDateFormat().setTimeZone(TimeZone.getTimeZone("GMT"));
它似乎沒有工作。時間修改仍然是一樣的。所以我嘗試設置正確的時區以匹配Date
對象中的時區。
final DateFormat valueFormatDate = new DateFormat("dd.MM.yyyy HH:mm");
valueFormatDate.getDateFormat().setTimeZone(TimeZone.getTimeZone("CET"));
這工作完美,因爲我的預期。但事情並不太容易,除了CET時區和CEST(中歐夏令時)之外,這個時間大約會再花費一個小時。當我嘗試在CEST時間使用日期時,由於在預計的基礎上增加了一個小時,所以沒有再次運行。我想這這將是解決他們設立「CEST」時區,而不是「CET」的,但我並沒有弄清楚如何獲得從Calendar
適當的時區,它總是返回CET。
反正最後我用了一個不是很好,但工作可靠的解決方案。
- 我有日期單元工廠方法以在該方法的一個位置
- 的結構,我轉換給定的
Date
是在GMT時區在第一
- 設置時區格式到GMT
- 在
DateTime
單元格上禁用時區修改。
這些步驟是絕對乾淨的,但它適用於CET和CEST日期。最終的代碼是在這裏:
public class DateUtils {
// formatter to convert from current timezone
private static final SimpleDateFormat DATE_FORMATTER_FROM_CURRENT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// formatter to convert to GMT timezone
private static final SimpleDateFormat DATE_FORMATTER_TO_GMT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
static {
// initialize the GMT formatter
final Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
DATE_FORMATTER_TO_GMT.setCalendar(cal);
}
public static Date toGMT(final Date base) {
try {
// convert to string and after that convert it back
final String date = DATE_FORMATTER_FROM_CURRENT.format(base);
return DATE_FORMATTER_TO_GMT.parse(date);
} catch (ParseException e) {
log.error("Date parsing failed. Conversion to GMT wasn't performed.", e);
return base;
}
}
}
而且還有一個工廠方法
/** builds date cell for header */
static WritableCell createDate(final int column, final int row, final Date value) {
final DateFormat valueFormatDate = new DateFormat("dd.MM.yyyy HH:mm");
valueFormatDate.getDateFormat().setTimeZone(TimeZone.getTimeZone("GMT"));
final WritableCellFormat formatDate = new WritableCellFormat(valueFormatDate);
// create cell
return new DateTime(column, row, toGMT(value), formatDate, DateTime.GMT);
}
感謝的答案,但問題仍然會出現:如果我使用的日期,並在構造函數中,我把DateTime.GMT ,小時是格林尼治標準時間,如果我不把DateTime.GMT格林威治時間。 看來,DateTime只使用GMT而不使用我的時區... – Enrico 2012-03-22 11:38:51