Time Conversion

Sort by

recency

|

266 Discussions

|

  • + 0 comments

    Simple solution in C++

    `
    string timeConversion(string s) {
        int n = s.size();
        string hourStr = s.substr(0,2);
        int hour = std::stoi( hourStr);
        if (s[n-2]=='P' && hour<12) {
            hour+=12 ;
            hourStr = to_string(hour);
        }
        if (s[n-2]=='A' && hour==12) {
            hourStr = "00";
        }
        s = hourStr.append(s.substr(2,n-4));
        
        return s;
    
    }
    
  • + 0 comments

    My solution in Java:

    public static String timeConversion(String s) {
        // Write your code here
            String[] time = s.split(":");
            int hour = Integer.valueOf(time[0]) + 12;
            if(time[2].contains("PM")){
                time[0] = String.valueOf(hour==24?hour-12:hour);
            } else {
                time[0] = time[0].contains("12")?"00":time[0];
            }
            return time[0]+":"+time[1]+":"+time[2].substring(0, 2);
        }
    
  • + 0 comments

    Using C++ Language.....

    string timeConversion(string s) {

    // Extract the period (AM/PM)
    string period = s.substr(s.length() - 2);
    // Extract the hour, minute, and second
    int hour = stoi(s.substr(0, 2));
    string minute_second = s.substr(2, 6);
    
    // Convert based on AM/PM period
    if (period == "AM") {
        if (hour == 12) {
            return "00" + minute_second; // Midnight case: 12 AM -> 00
        } else {
            return s.substr(0, 8);  // Keep the time as it is, remove AM/PM
        }
    } else {  // PM case
        if (hour == 12) {
            return "12" + minute_second;  // Keep the time as it is for 12 PM
        } else {
            return to_string(hour + 12) + minute_second;  // Add 12 to PM times
        }
    }
    

    }

  • + 0 comments

    python without using time module

    def timeConversion(s):
        # Write your code here
        hrs = "12"
        splitted = s.split(":")
        print(splitted)
        if "PM" in splitted[2][2:]:
            if "12" not in splitted[0]:
                hrs = str(int(hrs) + int(splitted[0]))
        if "AM" in splitted[2][2:]:
            if "12" not in splitted[0]:
                hrs = splitted[0]
            else:
                hrs = "00"
        return hrs+":"+splitted[1]+":"+splitted[2][:2]
    
  • + 0 comments

    Python One Liner using time module:

    import time
    def timeConversion(s):
        # Write your code here
        return time.strftime("%H:%M:%S", time.strptime(s, "%I:%M:%S%p"))