java - 将 HH:MM:SS (AM/PM) 的字符串时间格式转换为秒
问题描述
所以我有这个任务要求我们按照 HH:MM:SSAM 或 HH:SS:MMPM 的顺序采用字符串格式的时间。限制是,如果格式错误,它不能运行,让它丢失任何形式的 AM 或 PM,丢失数字,或者如果它是 24 小时格式。
我有整个想法,但是对于我的陈述,它给了我以下错误:
二元运算符“>”的错误操作数类型无法比较的类型:String 和 int
我是否不正确地转换它们或者我做错了什么?
public static void main(String args[]) {
//Test Methods
String fullTime1 = "03:21:36AM";
secondsAfterMidnight(fullTime1);
}
public static int secondsAfterMidnight(String time) {
String[] units = time.split(":");
int hours = Integer.parseInt(units[0]);
int minutes = Integer.parseInt(units[1]);
int seconds = Integer.parseInt(units[2]);
int totalSeconds = 0;
if (units[0] > 12 || units[1] > 59 || units[2] > 59) { //1st Error applies to these three, units[0] > 12 units[1] > 59 units[2] > 59
return -1;
} else if (time.equalsIgnoreCase("AM") || time.equalsIgnoreCase("PM")) {
totalSeconds = (hours * 3600) + (minutes * 60) + (seconds);
} else if (time.equalsIgnoreCase("AM") && units[0] == 12) { //2nd Error applies to this units[0] == 12
totalSeconds = (minutes * 60) + (seconds);
} else {
return -1;
}
return totalSeconds;
}
解决方案
units
是String类型,您正在尝试将其与int进行比较,因此会出现编译时错误。
您需要将String转换为int然后进行比较,如下所示:
Integer.parseInt(units[0]) > 12
等等等等。
此外,您可以利用已经存在的 java-8 的LocalTime来查找特定时间的秒数,而不是重新发明轮子:
public static int secondsAfterMidnight(String time) {
LocalTime localTime = LocalTime.parse(time, DateTimeFormatter.ofPattern("hh:mm:ss a"));
return localTime.toSecondOfDay();
}
推荐阅读
- javascript - 如何访问动态创建的锚标签jquery的数据属性
- reactjs - 如果 react-script 比 3.0.0 新,则会出现错误消息“'Office' is not defined no-undef”
- hybris - 如何配置以 Z 价格买 X 送 Y 的促销活动?
- python - 在 Windows 上使用 matplotlib 将输出渲染为 gif 的问题
- python - TypeError:预期的字符串或类似字节的对象 - Python (boto3)
- android - Android (Kotlin) 无法识别 Mockito
- matlab - 如何在 Matlab 中计算朴素贝叶斯后验概率
- maven - 如何为 Maven 插件指定默认目标?
- azure - 使用 Azure CLI 在 Azure DataLake gen 2 中创建文件夹
- drake - 改变视觉几何的事件