![](/img/trans.png)
[英]JodaTime: How to get a String representation in the format “HH:mm Z” from a 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.