Tommy Vidrio
Tommy Vidrio

Reputation: 33

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

So I have this assignment that is asking us to take in a String format of time in the order of HH:MM:SSAM or HH:SS:MMPM. The constraint is that it cannot run if it is in wrong format, let it be missing any form of the AM or PM, missing a number, or if it is in 24 Hour Format.

I have the whole idea down, however for my statements, it is giving me the error of:

bad operand types for binary operator '>' incomparable types: String and int

Did I convert them improperly or am I doing something else wrong?

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

Upvotes: 1

Views: 1268

Answers (5)

Anonymous
Anonymous

Reputation: 86276

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

Let’s try it out using the test code from your question:

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

12096

This is the recommended way for production code.

Only if you are doing an exercise training string manipulation, you should use one of the other answers.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Upvotes: 0

prasad_
prasad_

Reputation: 14287

I haven't verified your logic to calculate the seconds, but this code has corrections:

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

Upvotes: 0

Nicholas K
Nicholas K

Reputation: 15423

units is of type String and you are trying to compare it with an int hence the compile time error.

You need to convert the String to an int and then compare it, as shown below :

Integer.parseInt(units[0]) > 12

so on and so forth.


Also rather than re-inventing the wheel, you can make use of the already existing java-8's LocalTime to find the number of seconds for a particular time:

public static int secondsAfterMidnight(String time) {
    LocalTime localTime = LocalTime.parse(time, DateTimeFormatter.ofPattern("hh:mm:ss a"));
    return localTime.toSecondOfDay();
}

Upvotes: 1

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

You have already parsed the String values and saved them in the variables hours , minutes, seconds. Then you can use those for the check in the if.

Also the presence of AM?PM in the Integer.parseInt() will cause NumberFormatException to avoid it remove the String part from the number by using regex.

Also for checking the presence of AM/PM you can use String.contains.

Please check the reformatted code below:

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

Upvotes: 1

Prashant
Prashant

Reputation: 5383

Please note that even though you have converted the String to int, you are still comparing String with int. There would also be a RuntimeException when you do this:

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

As units[2] will contain 36AM. So you should be using substring() to remove the "AM/PM" part.

Upvotes: 1

Related Questions