简体   繁体   中英

Parsing HH:mm (with two digits minute) to LocalTime with JodaTime

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM