简体   繁体   English

使用JodaTime将HH:mm(每分钟两位)解析为LocalTime

[英]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.

相关问题 JodaTime:如何从LocalTime获取格式为“ HH:mm Z”的字符串表示形式 - JodaTime: How to get a String representation in the format “HH:mm Z” from a LocalTime 模式“YYYY-MM-dd HH:mm:ss Z”导致解析异常,其中Jodatime没有 - Pattern “YYYY-MM-dd HH:mm:ss Z” causes parsing exception where Jodatime did not 如何将 LocalTime 正确格式化为 HH:MM? - How to properly format LocalTime to HH:MM? JodaTime LocalDate / LocalTime无法使用自定义JSON序列化器类进行解析 - JodaTime LocalDate/LocalTime not Parsing with custom JSON Serializer classes 如何区分两个JodaTime LocalTime邮票? - How to get the difference between two JodaTime LocalTime stamps? 将String转换为Joda LocalTime格式(HH:mm:ss)并删除毫秒 - Convert String to Joda LocalTime format (HH:mm:ss) and Remove milliseconds JodaTime IllegalArgumentException无效格式“ yyyy-MM-dd hh:mm:ss” - JodaTime IllegalArgumentException Invalid format “yyyy-MM-dd hh:mm:ss” 使用java8中的单个DateTimeFormatter解析HH:mm:ss和H:mm:用于LocalTime的ss - Parse HH:mm:ss and H:mm:ss for LocalTime using single DateTimeFormatter in java8 Jackson objectMapper,试图将 LocalDate 序列化为“yyyy-MM-dd”,将 LocalTime 序列化为“HH:mm:ss” - Jackson objectMapper, trying to serialize LocalDate into "yyyy-MM-dd" and LocalTime into "HH:mm:ss" 如何将“String HH:MM”转换为“int hour HH”和“int minute MM” - How can I convert a “String HH:MM” to a “int hour HH” and “int minute MM”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM