使用新日期创建Java日期时忽略夏令时(aDate.getTime()+ aTime.getTime()) [英] Daylight saving ignored when creating a Java Date using new Date(aDate.getTime() + aTime.getTime())

查看:285
本文介绍了使用新日期创建Java日期时忽略夏令时(aDate.getTime()+ aTime.getTime())的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently verifying that a generated Excel sheet contains a correctly-rendered "time stamp" whose date and time part are in separate cells, and whose format is adjusted by a locale.

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

My test case fails, as when I read back the Excel sheet's time from a String, somehow daylight saving seems to be ignored.

这是我的Java代码:

Here's my Java code:

    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


推荐答案

遵循Martin和Matt的建议,这里是我的最终程序片段:

Following both Martin's and Matt's suggestions, here is my final program snippet:

    // 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)); 

这篇关于使用新日期创建Java日期时忽略夏令时(aDate.getTime()+ aTime.getTime())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆