使用新日期创建Java日期时忽略夏令时(aDate.getTime()+ aTime.getTime())

我目前正在validation生成的Excel工作表是否包含正确呈现的“时间戳”,其日期和时间部分位于不同的单元格中,其格式由区域设置调整。

我的测试用例失败了,因为当我从字符串中读回Excel工作表的时间时,不知何故,夏令时似乎被忽略了。

这是我的Java代码:

Date now = new Date(); // [... other code, creating and reading the Excel sheet etc. ...] // from an Excel sheet String dateString = cellB2.getStringCellValue(); // eg, 3.7.2013 String timeString = cellB3.getStringCellValue(); // eg, 13:38:09 TimeZone tz = TimeZone.getDefault(); // Berlin, CEST dateFormat.setTimeZone(tz); // dateFormat is result of DateFormat.getDateInstance(DateFormat.MEDIUM, locale); eg with locale "cs_CZ" timeFormat.setTimeZone(tz); // timeFormat is result of DateFormat.getTimeInstance(DateFormat.MEDIUM, locale); eg with locale "cs_CZ" // try to parse the time / date strings using the expected format Date actualDate = dateFormat.parse(dateString); // eg, Wed Jul 03 00:00:00 CEST 2013 Date actualTime = timeFormat.parse(timeString); // eg Thu Jan 01 13:38:09 CET 1970 // now: eg Wed Jul 03 13:38:09 CEST 2013 // actualDateTime: eg 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" 

然后,只需像这样制作一个Date String:

 String dateTime = cellB2.getStringCellValue() + " " + cellB3.getStringCellValue(); 

然后你可以解析它…我实际上没有测试它,但它应该给你的想法,也许你需要检查模式字符串,这里是参考:

http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

问候

根据Martin和Matt的建议,这是我的最终程序片段:

  // from an Excel sheet String dateString = cellB2.getStringCellValue(); String timeString = cellB3.getStringCellValue(); TimeZone tz = TimeZone.getDefault(); // NEW! DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, l); dateTimeFormat.setTimeZone(tz); Date actualDateTime = dateTimeFormat.parse(dateString + " " + timeString); assertFalse(now.after(actualDateTime)); 

设置actualTime后,我必须做出以下区分:

  if (tz.inDaylightTime(actualDate)) { actualTime = new Date(actualTime.getTime() + 1000 * 60 * 60); } 

由于仅限时间的字符串将始终在1970年1月1日生成日期,因此永远不会考虑夏令时(至少不适用于我的柏林案例),我必须手动进行调整。

java中的日期不会自动添加夏令时。 这是因为java Date是按纪元(自1970年1月1日以来的秒数)计算的,并且表示UTC时间。

如果您希望自己使用的课程自动更正夏令时,可以使用内置的Calendar课程或Joda Time 。 我真的建议看一下Joda Time。 它比java.util.Date更好java.sql.Date和java.util.Calendar相结合! 处理一个真正完整的时间库比处理3个不同的时间库并尝试在它们之间进行转换要容易得多。

此外,正如一个有趣的旁边显示DST有多困难,请看这个video – 在大约4分钟的时间点它解释了不同国家如何实施DST以及这给每个人带来的麻烦。