3

現在、生成された 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
4

4 に答える 4

2

ロバート、

あなたのソリューションは機能しますが、それは別の回避策を回避するようなものであり、コードがより複雑になり、維持が難しくなると思います. このパターンで 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

よろしく

于 2013-07-03T14:44:25.910 に答える
1

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)); 
于 2013-07-03T15:06:09.740 に答える
0

actualTime を設定した後、次の区別を行う必要があります。

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

時刻のみの文字列は常に 1970 年 1 月 1 日の日付になるため、夏時間は考慮されず (少なくとも私のベルリンの場合は考慮されません)、手動で調整する必要があります。

于 2013-07-03T14:27:42.280 に答える