I was attempting the Time Conversion challenge on Hackerrank, but for some reason, the hour field in the 24-hour representation always comes out empty. Here's the challenge -
Problem Statement
Given a time in AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock and 12:00:00 on a 24-hour clock.
Another problem seems to be that the seconds always appears to be of 1 digit. For instance, if the input is 07:05:45PM
, my Hackerrank output is :05:4
.
But, the code runs just fine in IntelliJ on my desktop -
1:24:23AM
1
24
23AM
01:24:23
Process finished with exit code 0
and
07:05:45PM
07
05
45PM
19:05:45
Process finished with exit code 0
As there's no way to debug the solution on hackerrank itself, I'm not sure what's wrong. Here's my code -
package algorithms.Warmup;
import java.util.Scanner;
/**
* Created by manishgiri on 1/6/16.
*/
public class TimeConversion {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String time = in.next();
String[] parts = time.split(":");
for(String part: parts){
System.out.println(part);
}
int hours = Integer.parseInt(parts[0]);
String minutes = (parts[1]);
String[] last = parts[2].split("");
String seconds = last[0]+last[1];
String timeZ = last[2]+last[3];
String finalHour = "";
if(timeZ.equalsIgnoreCase("PM")) {
if(hours == 12) {
finalHour = Integer.toString(12);
}
else {
finalHour = Integer.toString(hours + 12);
}
}
else if(timeZ.equalsIgnoreCase("AM")) {
if(hours == 12) {
finalHour = "00";
}
else if(hours == 10 || hours == 11) {
finalHour = Integer.toString(hours);
}
else {
finalHour = "0"+hours;
}
}
System.out.println(finalHour+":"+minutes+":"+seconds);
}
}