2013-04-13 5 views
7

この単純なJUnitアサーションはなぜ失敗しますか?Java SimpleDateFormatの解析結果が1時間遅れます(そして、はい、タイムゾーンを設定します)

public void testParseDate() throws ParseException { 
    final SimpleDateFormat formatter = new SimpleDateFormat(
      "yyyy-MM-dd HH:mm:ss z"); 
    formatter.setTimeZone(UTC); 
    final Calendar c = new GregorianCalendar(); 
    c.setTime(formatter.parse("2013-03-02 11:59:59 UTC")); 

    assertEquals(11, c.get(HOUR_OF_DAY)); 
} 

グレゴリオ暦のデフォルトコンストラクタは、ローカルタイムゾーンを使用して、私は一日の時間が11であると予想されているだろうが、JUnitのによると、一日の時間が12

junit.framework.AssertionFailedError: expected:<11> but was:<12> 
at junit.framework.Assert.fail(Assert.java:47) 
    ... snip ... 
+2

夏時間。 –

+0

いいえ、そうではありませんでした。私は夏時間を避けるためにどこでもUTCを使用しようとしています。私はそれによってたくさん噛まれま​​した。 –

答えて

6

ですこの機械。それがUTCと異なる場合は、この動作が発生します。 GregorianCalendar(TimeZone)コンストラクタを使用してUTCを渡してみてください。

これは動作します:あなたはまた、カレンダーのタイムゾーン/サマータイムを設定する必要があり

public void testParseDate() throws Exception { 

    TimeZone UTC = TimeZone.getTimeZone("UTC"); 

    // Create a UTC formatter 
    final SimpleDateFormat formatter = new SimpleDateFormat(
      "yyyy-MM-dd HH:mm:ss z"); 
    formatter.setTimeZone(UTC); 

    // Create a UTC Gregorian Calendar (stores internally in UTC, so 
    // get(Calendar.HOUR_OF_DAY) returns in UTC instead of in the 
    // local machine's timezone. 
    final Calendar c = new GregorianCalendar(UTC); 

    // Ask the formatter for a date representation and pass that 
    // into the GregorianCalendar (which will convert it into 
    // it's internal timezone, which is also UTC. 
    c.setTime(formatter.parse("2013-03-02 11:59:59 UTC")); 

    // Output the UTC hour of day 
    assertEquals(11, c.get(Calendar.HOUR_OF_DAY)); 
} 
+0

それだけです!テストは今すぐ通過します。 –

1

documentationから取得したこのスニペットをご覧ください。

// create a Pacific Standard Time time zone 
SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]); 

// set up rules for daylight savings time 
pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); 
pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); 

// create a GregorianCalendar with the Pacific Daylight time zone 
// and the current date and time 
Calendar calendar = new GregorianCalendar(pdt); 
+1

閉じる、私はUTCを使用しなければならず、dstについて心配しない。 :) –

関連する問題