java - 使用 new Date(aDate.getTime() + aTime.getTime()) 创建 Java 日期时忽略夏令时

标签 java date timezone

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

相关文章:

java - GeoPoint 中的空指针异常

c# - 是否可以在 Visual Studio 中调试时编辑代码,例如在 Eclipse(Java)中

php - 使用 php 和 sql 将 dd/mm/yyyy 转换为 yyyy/mm/dd

MySQL 时间戳到日期时间的转换

python - 如何在 Django 中设置时区

java - 如何获取不同时区的本地时间?

ios - 将时间戳转换为其他时区(快速)

java - 如何在从 Spark 使用 Kafka 时获取偏移量 ID,将其保存在 Cassandra 中并使用它来重启 Kafka?

java.lang.NoSuchFieldError : PUBLIC_ONLY while using Box api in android in signed build 错误

php - 周日和周六的 php 日期?