我目前正在验证生成的 Excel 工作表是否包含正确呈现的“时间戳”,其日期和时间部分位于不同的单元格中,并且其格式已根据语言环境进行了调整。
我的测试用例失败了,因为当我从字符串中读回 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
最佳答案
罗伯特,
您的解决方案会奏效,但我认为这就像用一种变通办法解决另一种变通办法,这会使您的代码更加复杂,因此更难维护。为什么不使用具有这种模式的 SimpleDateFormat:
"dd.MM.YYYY kk:mm:ss"
然后,像这样制作一个日期字符串:
String dateTime = cellB2.getStringCellValue() + " " + cellB3.getStringCellValue();
然后你就可以解析了...我没有实际测试过,但它应该给你思路,也许你需要检查模式字符串,这里是引用:
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
问候
关于java - 使用 new Date(aDate.getTime() + aTime.getTime()) 创建 Java 日期时忽略夏令时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17447481/