JDK8 java.time.LocalTime与自定义模式
问题描述:
为什么该测试通过任何人都可以向我解释: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
这是一个有点不合逻辑的,不是吗?
答
摘要:使用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”。
答
“hh”为1-12小时,需要额外的am/pm标志。将其更改为'HH',它应该按预期工作。
另请注意,在您的第一次测试中,您可能需要ISO_LOCAL_TIME
。