带自定义模式的JDK8 java.time.LocalTime

Pav*_*aev 1 java java-8 java-time

任何人都可以向我解释为什么这个测试通过:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

第二次测试捕获的异常如下所示:

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
Run Code Online (Sandbox Code Playgroud)

这有点不合逻辑,不是吗?

ass*_*ias 8

'hh'是1-12小时,需要额外的上午/下午标志.将其更改为"HH",它应该按预期工作.

另请注意,在您的第一次测试中,您可能需要ISO_LOCAL_TIME.