【发布时间】:2019-11-11 06:18:38
【问题描述】:
所以我一直在尝试将字符串 Hour 从 12 小时格式转换为 24 小时格式,代码如下:
public String convertAM(String checkinCheckoutTime) {
String withoutAM = checkinCheckoutTime.replaceAll("AM", "").trim();
if (withoutAM.length() == 1 || withoutAM.length() == 2) {
return LocalTime.parse(
withoutAM + ":00 AM", DateTimeFormatter.ofPattern("hh:mm a", Locale.US))
.format(DateTimeFormatter.ofPattern("HH:mm"));
} else {
return LocalTime.parse(
checkinCheckoutTime, DateTimeFormatter.ofPattern("hh:mm a", Locale.US))
.format(DateTimeFormatter.ofPattern("HH:mm"));
}
}
我在这次测试中获得了绿色:
@Test
public void convertCheckinCheckoutTime12AMWithSpace() {
String checkOutTime = "12 AM";
String expectedCheckOutTime = "00:00";
String result = this.service.convertAM(checkOutTime);
Assert.assertEquals(expectedCheckOutTime, result);
}
但是在这个测试中我得到了错误:
@Test
public void convertCheckinCheckoutTimeAMNoRangeWithSpace() {
String checkOutTime = "3 AM";
String expectedCheckOutTime = "3:00";
String result = this.service.convertAM(checkOutTime);
Assert.assertEquals(expectedCheckOutTime, result);
}
错误是:
java.time.format.DateTimeParseException: Text '3:00 AM' could not be parsed at index 0
我可以知道凌晨 3 点出了什么问题吗?提前谢谢你
【问题讨论】:
-
在格式化程序中将
hh替换为h -
谢谢,它适用于个位数小时
标签: java time datetime-parsing java-time