[英]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. 我需要解析“ 10:10”之类的字符串并创建一个LocalTime对象。 If the string is like "10:1" the parsing should throw a IllegalArgumentException. 如果字符串类似于“ 10:1”,则解析应引发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
DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendHourOfDay(2)
.appendLiteral(":").appendMinuteOfHour(2).toFormatter();
but "10:1" is still converted...how to do it? 但是“ 10:1”仍会转换...该怎么做?
Use appendFixedDecimal
method of DateTimeFormatBuilder . 使用DateTimeFormatBuilder的 appendFixedDecimal
方法。 You pass the numDigits
arguments which is a fixed number of digits instead of minimum required. 您传递numDigits
参数,该参数是固定位数而不是最低要求。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.