2015-03-02 26 views
1

爲什麼該測試通過任何人都可以向我解釋:JDK8 java.time.LocalTime與自定義模式

import org.junit.Assert; 
import org.junit.Test; 

import java.time.LocalTime; 
import java.time.format.DateTimeFormatter; 
import java.time.format.DateTimeParseException; 

import static org.hamcrest.core.Is.is; 

public class BasicTest extends Assert{ 

    @Test 
    public void testLocalTimeWithPredefinedPattern() throws Exception { 
     DateTimeFormatter dtf = DateTimeFormatter.ISO_TIME; 
     LocalTime time = LocalTime.parse("10:11:12", dtf); 
     assertThat(time.toString(), is("10:11:12")); 
    } 

    /** 
    * It's a kind of bug from my side of view 
    */ 
    @Test(expected = DateTimeParseException.class) 
    public void testLocalTimeWithCustomPattern() throws Exception { 
     DateTimeFormatter dtf = DateTimeFormatter.ofPattern("hh:mm:ss"); 
     LocalTime time = LocalTime.parse("10:11:12", dtf); 
    } 
} 

異常的第二次測試是抓是這樣的:

java.time.format.DateTimeParseException: Text '10:11:12' could not be parsed: Unable to obtain LocalTime from TemporalAccessor: {MilliOfSecond=0, MinuteOfHour=11, MicroOfSecond=0, SecondOfMinute=12, NanoOfSecond=0, HourOfAmPm=10},ISO of type java.time.format.Parsed 

這是一個有點不合邏輯的,不是嗎?

回答

3

摘要:使用ISO_LOCAL_TIME,而不是ISO_TIME並使用「H」,而不是「h」。

當使用java.time調查解析問題時,請務必檢查錯誤消息。在這種情況下,該消息是:

Text '10:11:12' could not be parsed: 
Unable to obtain LocalTime from TemporalAccessor: 
{MilliOfSecond=0, MinuteOfHour=11, MicroOfSecond=0, 
SecondOfMinute=12, NanoOfSecond=0, HourOfAmPm=10},ISO 
of type java.time.format.Parsed 

(格式化爲易於在StackOverflow的閱讀)

該消息告訴我們,所填充的字段是:

  • HourOfAmPm = 10
  • MinuteOfHour = 11
  • SecondOfMinute = 12

事實上,它是「HourOfAmPm」而不是「HourOfDay」告訴我們已經使用了錯誤的模式字母,「h」而不是「H」。關鍵在於,在java.time中,填充字段的集合比舊格式化程序DateFormat更嚴格。要獲得LocalTime,必須指定「HourOfDay」或「AmPmOfDay」和「HourOfAmPm」。

8

「hh」爲1-12小時,需要額外的am/pm標誌。將其更改爲'HH',它應該按預期工作。

另請注意,在您的第一次測試中,您可能需要ISO_LOCAL_TIME