使用JodaTime将HH:mm(两分钟为分钟)解析为LocalTime [英] Parsing HH:mm (with two digits minute) to LocalTime with JodaTime

查看:298
本文介绍了使用JodaTime将HH:mm(两分钟为分钟)解析为LocalTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析"10:10"之类的字符串并创建一个LocalTime对象. 如果字符串类似于"10:1",则解析应引发IllegalArgumentException. (分钟必须是两位数)

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)

所以我做到了

String time = "10:1";
LocalTime myLT;
DateTimeFormatter dtf = DateTimeFormat.forPattern("HH:mm");
myLT = dtf.parseLocalTime(time);

我也尝试过使用DateTimeFormatter

I tried also with DateTimeFormatter

DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendHourOfDay(2)
.appendLiteral(":").appendMinuteOfHour(2).toFormatter();

但是"10:1"仍会转换...怎么办?

but "10:1" is still converted...how to do it?

推荐答案

使用

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

这篇关于使用JodaTime将HH:mm(两分钟为分钟)解析为LocalTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆