使用 JodaTime 将 HH:mm(两位数分钟)解析为 LocalTime
Parsing HH:mm (with two digits minute) to LocalTime with JodaTime
我需要解析像“10:10”这样的字符串并创建一个 LocalTime 对象。
如果字符串类似于“10:1”,则解析应抛出 IllegalArgumentException。 (分钟必须是两位数)
所以我做了这个
String time = "10:1";
LocalTime myLT;
DateTimeFormatter dtf = DateTimeFormat.forPattern("HH:mm");
myLT = dtf.parseLocalTime(time);
我也尝试使用 DateTimeFormatter
DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendHourOfDay(2)
.appendLiteral(":").appendMinuteOfHour(2).toFormatter();
但是“10:1”还是被转换了...怎么办?
使用DateTimeFormatBuilder的appendFixedDecimal
方法。您传递的 numDigits
参数是固定位数而不是最低要求。
在你的情况下它会是这样的(我自己还没有测试过)
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendFixedDecimal(DateTimeFieldType.clockhourOfDay(),2)
.appendFixedDecimal(DateTimeFieldType.minuteOfHour(),2)
.toFormatter()
.withZoneUTC();
我需要解析像“10:10”这样的字符串并创建一个 LocalTime 对象。 如果字符串类似于“10:1”,则解析应抛出 IllegalArgumentException。 (分钟必须是两位数)
所以我做了这个
String time = "10:1";
LocalTime myLT;
DateTimeFormatter dtf = DateTimeFormat.forPattern("HH:mm");
myLT = dtf.parseLocalTime(time);
我也尝试使用 DateTimeFormatter
DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendHourOfDay(2)
.appendLiteral(":").appendMinuteOfHour(2).toFormatter();
但是“10:1”还是被转换了...怎么办?
使用DateTimeFormatBuilder的appendFixedDecimal
方法。您传递的 numDigits
参数是固定位数而不是最低要求。
在你的情况下它会是这样的(我自己还没有测试过)
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendFixedDecimal(DateTimeFieldType.clockhourOfDay(),2)
.appendFixedDecimal(DateTimeFieldType.minuteOfHour(),2)
.toFormatter()
.withZoneUTC();