Time Conversion

Sort by

recency

|

5163 Discussions

|

  • + 0 comments

    string timeConversion(string s) { string hour = s.substr(0, 2); // starts from 0 and len = 2 string amPM = s.substr(8); // from 0 to the rest

    string result = "";
    if (hour == "12") {
        result += (amPM == "PM") ? "12" : "00";
    } else {
        result += (amPM == "PM") ? to_string(stoi(hour) + 12) : hour;
    }
    
    result += s.substr(2, 6); // starts from the index 2 and len = 6
    return result;
    

    }

  • + 0 comments

    Java 15

    int hour = Integer.parseInt(s.substring(0, 2));
         if (s.charAt(8) == 'P') {
             if (hour != 12)
                 hour = (hour + 12) % 24;
         } else if (hour == 12)
             hour = (hour + 12) % 24;
    
         String hr = Integer.toString(hour);
         if (hr.length() == 1)
             hr = "0".concat(hr);
    
         return hr.concat(s.substring(2, 8));
    
  • + 0 comments

    Java Solution

    Using a boolen value to indicate the time am/pm.

    public static String timeConversion(String s) {
        // Write your code here
            StringBuilder finalTime = new StringBuilder("");
            boolean isPm = false;
            for(int i = 0 ; i < s.length() ; i++){
                finalTime.append(s.charAt(i));
                int secoundLastEle  = s.length()-2;
                if(s.charAt(secoundLastEle) == 'A'){
                    isPm = false;
                }
                else {
                    isPm = true; 
                }
            }
            
            finalTime.deleteCharAt(finalTime.length()-1); // last deletecharAt 
            finalTime.deleteCharAt(finalTime.length()-1); // secound last deletecharAt 
            
                
                String subSet = finalTime.substring(0,2);
                int convert_time = Integer.parseInt(subSet);
                
                if(isPm){
                    if(convert_time != 12){
                        convert_time += 12;
                    }
                    String replace_convert_time = String.valueOf(convert_time);
                    finalTime.replace(0,2,replace_convert_time);
                }
                else{
                    if(subSet.equals("12")){
                        finalTime.replace(0,2,"00");
                    }
                }
            
            return finalTime.toString();
        }
    
  • + 0 comments

    public static string timeConversion(string s) => DateTime.ParseExact(s, "hh:mm:sstt", CultureInfo.InvariantCulture).ToString("HH:mm:ss"); `

  • + 0 comments

    from datetime import datetime def timeConversion(s):

    a = datetime.strptime(s, "%I:%M:%S%p")
    return a.strftime("%H:%M:%S")
    

    if name == 'main':

    s = input()
    
    result = timeConversion(s)
    print(result)![](https://)