繁体   English   中英

将HH:MM:SS(AM / PM)的字符串时间格式转换为秒

[英]Converting String time format of HH:MM:SS (AM/PM) into Seconds

所以我有这个任务要求我们按照HH:MM:SSAM或HH:SS:MMPM的顺序采用String格式的时间。 限制是,如果格式错误,它将无法运行,让它丢失任何形式的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();
}

请注意,即使您已将String转换为int ,您仍然在将Stringint进行比较。 执行此操作时还会出现RuntimeException

 int seconds = Integer.parseInt(units[2]);

units[2]将包含36AM 所以你应该使用substring()来删除“AM / PM”部分。

您已经解析了String值并将它们保存在变量hours , minutes, seconds 然后你可以使用那些来检查if

此外,在Integer.parseInt()存在AM?PM将导致NumberFormatException避免它使用正则表达式从数字中删除String部分。

另外,为了检查AM/PM的存在,您可以使用String.contains

请检查下面重新格式化的代码:

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].replaceAll("[^0-9]", ""));
    int totalSeconds = 0;
    if (hours > 12 || minutes > 59 || seconds > 59) {  
        return -1;
    } else if (time.contains("AM") || time.contains("PM")) {
        totalSeconds = (hours * 3600) + (minutes * 60) + (seconds);
    } else if (time.contains("AM") && hours == 12) { 
        totalSeconds = (minutes * 60) + (seconds);
    } else {
        return -1;
    }
    return totalSeconds;
}

我还没有验证你计算秒数的逻辑,但是这段代码有更正:

public static int secondsAfterMidnight(String time) {

    String[] units = time.split(":");
    int hours = Integer.parseInt(units[0]);
    int minutes = Integer.parseInt(units[1]);

    int seconds = 0;
    String amPm = "";

    if ( units[2].contains("AM") || units[2].contains("PM") ||
            units[2].contains("am") || units[2].contains("pm") ) {
        seconds = Integer.parseInt(units[2].substring(0, 2));
        amPm = units[2].substring(2);
    }
    else {
        seconds = Integer.parseInt(units[2]);
    }

    int totalSeconds = 0;

    if (hours > 12 || minutes > 59 || seconds > 59) {
        return -1;
    } else if (amPm.equalsIgnoreCase("AM") || amPm.equalsIgnoreCase("PM")) {
        totalSeconds = (hours * 3600) + (minutes * 60) + (seconds);
    } else if (amPm.equalsIgnoreCase("AM") && hours == 12) {
        totalSeconds = (minutes * 60) + (seconds);
    } else {
        return -1;
    }

    return totalSeconds;
}

java.time

static DateTimeFormatter timeFormatter
        = DateTimeFormatter.ofPattern("HH:mm:ssa", Locale.ENGLISH);

public static int secondsAfterMidnight(String time) {
  try {
    return LocalTime.parse(time, timeFormatter).get(ChronoField.SECOND_OF_DAY);
  } catch (DateTimeParseException dtpe) {
    return -1;
  }
} 

让我们使用您问题中的测试代码进行尝试:

  String fullTime1 = "03:21:36AM";
  System.out.println(secondsAfterMidnight(fullTime1));

12096

这是生产代码的推荐方法。

只有在进行练习训练字符串操作时,才应使用其他答案之一。

链接: Oracle教程:日期时间,解释如何使用java.time。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM