我目前正在验证生成的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