我目前正在驗證生成的Excel工作表包含正確呈現的「時間戳」,其日期和時間部分在單獨的單元格中,並且其格式通過語言環境進行調整。使用新日期創建Java日期時忽略夏令時(aDate.getTime()+ aTime.getTime())
我的測試用例失敗了,因爲當我從字符串中讀取Excel工作表的時間時,似乎忽略了夏令時。
這裏是我的Java代碼:
Date now = new Date();
// [... other code, creating and reading the Excel sheet etc. ...]
// from an Excel sheet
String dateString = cellB2.getStringCellValue(); // e.g., 3.7.2013
String timeString = cellB3.getStringCellValue(); // e.g., 13:38:09
TimeZone tz = TimeZone.getDefault(); // Berlin, CEST
dateFormat.setTimeZone(tz); // dateFormat is result of DateFormat.getDateInstance(DateFormat.MEDIUM, locale); e.g. with locale "cs_CZ"
timeFormat.setTimeZone(tz); // timeFormat is result of DateFormat.getTimeInstance(DateFormat.MEDIUM, locale); e.g. with locale "cs_CZ"
// try to parse the time/date strings using the expected format
Date actualDate = dateFormat.parse(dateString); // e.g., Wed Jul 03 00:00:00 CEST 2013
Date actualTime = timeFormat.parse(timeString); // e.g. Thu Jan 01 13:38:09 CET 1970
// now: e.g. Wed Jul 03 13:38:09 CEST 2013
// actualDateTime: e.g. Wed Jul 03 12:48:07 CEST 2013
Date actualDateTime = new Date(actualDate.getTime() + actualTime.getTime());
assertFalse(now.after(actualDateTime)); // fails
首先我不喜歡你解析的方式。我首先要連接兩個輸入字符串(在它們之間有空格),然後只進行一個解析。我不是100%確定當你解析一個沒有日期值的時間時會發生什麼,可能是它將當前日期作爲默認值,還是真的考慮0 + timeConversion?我希望看到什麼actualDate和ActualTime返回,如果你格式化他們...此代碼以前工作? – Martin
不,代碼沒有工作過。 關於僅使用一個解析:我無法找到一種方法從DateFormats中獲取模式而不投射 - 是否有任何? – RobertG
關於解析一個只顯示時間的字符串,你可能是對的:評論顯示actualTime似乎是關閉一個小時(CET而不是CEST),但我想知道是否可以阻止。顯然,setTimeZone()不起作用。 – RobertG