2

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


    }
}
1
  • Since there is no debug. You could replace the split for the last part AM and pm. You could just check if it String#contains AM or PM. Afterwards you could use String#replaceAll with the regex \\D. That way you would replace the AM and PM and would only have the seconds left. Maybe Hackerrank does a bad job with the split(""). Since it running for me either i can just an other way to solve it that might be working. Commented Jan 6, 2016 at 10:59

11 Answers 11

2

Try the code below. Hope the comments will help to understand the logic.

static String timeConversion(String s) {
    // Split the string by :
    String[] sTime = s.split(":");

    int x = 0;

    // if PM and hours >12, add additional 12 to hours
    // for AM and hour = 12, set hour to 00
    if(sTime[sTime.length - 1].contains("PM") && !sTime[0].equals("12"))
        x = 12;

    String val1 = "";
    if(x == 12)
        val1 = (Integer.parseInt(sTime[0]) + x) + "";
    else {
        if(sTime[0].equals("12") && sTime[sTime.length - 1].contains("AM"))
            val1 = "00";
        else
            val1 = sTime[0];
    }

    // merge the string and return the result
    String result = val1 + ":" + sTime[1] + ":" + sTime[2].substring(0,2);
    return result;
}

Cheers!

Sign up to request clarification or add additional context in comments.

Comments

1

I do not know why there is inconsistency between your JRE environment and Hackerrank environment. But if we came to your question, in hackerrank your code splits part[2] into 5 parts, leading empty string.

Which means if you update

String seconds = last[0]+last[1];
String timeZ = last[2]+last[3];

as

String seconds = last[1]+last[2];
String timeZ = last[3]+last[4];

it should run,

and to prevent initial empty string, there is some suggestions you can find below:

How to prevent java.lang.String.split() from creating a leading empty string?

Comments

0

You can try this for hackerrank -

 public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String time = in.next();
        int hours;
        String hrs = time.substring(0,2);
        hours = Integer.parseInt(hrs);
        String mins = time.substring(3,5);
        String secs = time.substring(6,8);
        String am_pm = time.substring(time.length()-2,time.length());
        if(am_pm.equalsIgnoreCase("PM") && !hrs.equalsIgnoreCase("12")){  
            hours += 12;
            hrs = Integer.toString(hours);
        }
        else if(am_pm.equalsIgnoreCase("AM") && hrs.equalsIgnoreCase("12")){
            hours = 0;
            hrs = "00";
        }
        System.out.println(hrs+":"+mins+":"+secs);
    }

Comments

0

You can try this..

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String time = in.next();

    String[] sTime = time.split(":");

    int x = sTime[sTime.length - 1].contains("PM") ? 12 : 0 ;

    String val1 = (x == 12) ?  (Integer.parseInt(sTime[0]) + x) + "" :  (sTime[0].equals("12") ? "00" : sTime[0]);

    String result = val1 + ":" + sTime[1] + ":" + sTime[2].substring(0,2);
    System.out.println(result);
}

Comments

0
public static String timecon(String s) {
    System.out.println(s.substring(0, 2));
    int test = Integer.valueOf(s.substring(0, 2));
    if ((s.substring(0, 2).equals("12")) && s.substring(8, 10).equals("AM")) {
        return "00" + ":" + s.substring(3, 8);
    } else if (s.substring(0, 2).equals("12") && (s.substring(8, 10).equals("PM"))) {
        return s.substring(0, 8);
    } else if (s.substring(8, 10).equals("AM")) {
        return s.substring(0, 8);
    }
    else {
        return test + 12 + ":" + s.substring(3, 8);
    }

}

Comments

0

You can try this in Java for Time Conversion Hackerrank

  /*
 * Complete the timeConversion function below.
 */
static String timeConversion(String s) {
    String h,m,sec;

    h = s.substring(0,2);
    m = s.substring(3,5);
    sec = s.substring(6,8);

    if(s.contains("PM") && !h.equals("12")){
        int inc = 12;
        inc += Integer.parseInt(h);
        h = inc + "";
    }
    if(s.contains("AM") && h.equals("12")){
        h = "00";
    }
    String milTime = h + ":" + m + ":" + sec;
    return milTime;
}

Comments

0

Try this:

public static String timeConversion(String s) {

int h = Integer.parseInt(s.substring(0,2));

if (h == 12) h = 0;

if (s.substring(8,9).equals("P")) h = h + 12;

return String.format("%02d", h) + s.substring(2,8);

}

Comments

0
public static string timeConversion(string s)
{
      var idate = DateTime.Parse(s);
      var odate = idate.TimeOfDay;
      return odate.ToString();
}

Comments

0

the most compact code, i think

function timeConversion(s) {
    // Write your code here
    let time=s.slice(0,10).split(':');
    // return(time);
    if((time[0]<12)&&(time[2].includes('PM'))){
        time[0]=parseInt(time[0])+12;
    }
    if((time[0]==12)&&(time[2].includes('AM'))){
        time[0]='00';
    }
    // return(time);
    return(time.join(':').slice(0,8));
}

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0
function timeConversion(s) {

    let split = s.split();
    let currenHour = s.slice(0, 2);

    let checkPm = split.filter((val) => val.includes("PM"));
    let checkAm = split.filter((val) => val.includes("AM"));

    if (checkPm != "") {
        if (currenHour != "12") {
            let newTime = Number(currenHour) + 12;
            let newArr = newTime.toString() + s.slice(2, 8);
            return (newArr);
        } else {
            return (s.slice(0, 8));
        }
    }
    if (checkAm != "") {
        if (currenHour != "12") {
            let newArr = s.slice(0, 8);
            return (newArr);
        } else {
            return ('00' + s.slice(2, 8,))
        }
    }
}

Comments

-1
def timeConversion(s):
    # time_r=s[:-2]
    am_pm=s[-2:]
    if am_pm=='PM' and s[:2]!='12':
    s=str(int(s[:2])+12) + s[2:]
    if am_pm=='AM' and s[:2]=='12':
        s="00" + s[2:]
    return s[:-2]

print(timeConversion("07:05:45PM"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.