首页 > 解决方案 > 将 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;
} 

标签: javastringdatetimecompiler-errors

解决方案


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

推荐阅读