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

你。 提交于 2019-12-24 13:26:27

问题


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:


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


来源:https://stackoverflow.com/questions/33106665/parsing-hhmm-with-two-digits-minute-to-localtime-with-jodatime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!