谁能向我解释为什么通过此测试:
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
这有点不合逻辑,不是吗?
最佳答案
摘要:使用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”。