Parsing HH:mm (with two digits minute) to LocalTim

2019-08-06 15:31发布

I need to parse a string like "10:10" and create a LocalTime object. If the string is like "10:1" the parsing should throw a IllegalArgumentException. (minute must be of two digits)

So I made this

String time = "10:1";
LocalTime myLT;
DateTimeFormatter dtf = DateTimeFormat.forPattern("HH:mm");
myLT = dtf.parseLocalTime(time);

I tried also with DateTimeFormatter

DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendHourOfDay(2)
.appendLiteral(":").appendMinuteOfHour(2).toFormatter();

but "10:1" is still converted...how to do it?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-06 15:44

Use appendFixedDecimal method of DateTimeFormatBuilder. You pass the numDigits arguments which is a fixed number of digits instead of minimum required.

In your case it would be something like (haven't tested it myself)

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendFixedDecimal(DateTimeFieldType.clockhourOfDay(),2)
    .appendFixedDecimal(DateTimeFieldType.minuteOfHour(),2)
    .toFormatter()
    .withZoneUTC();
查看更多
登录 后发表回答