Time Conversion

Sort by

recency

|

347 Discussions

|

  • + 0 comments

    A python 3 solution

    def timeConversion(s):
        # Write your code here
        hh = int(s[0:2])
        mm = s[3:5] 
        ss = s[6:8]
        period= s[8:9]
        if period == "P" and hh<12:
            hh +=12
        elif period =="A" and hh == 12 :
            hh = 0
        hour = f"{hh:02d}" if hh<10 else str(hh)
        return f"{hour}:{mm}:{ss}"
    
  • + 0 comments

    Here is a C++ solution:

    string timeConversion(string s) {
        int hh = stoi(s.substr(0, 2));
        string mm = s.substr(3, 2);
        string ss = s.substr(6, 2);
        string time,hour;
            
        if (s.substr(8, 1) == "P") {  
            hour = (hh!=12 ? to_string(hh+=12) : to_string(hh));     
            time = hour + ":" + mm + ":" + ss;
        }
        else {
            if(hh==12)
                hour = "00";
            else
                hour = (hh<10 ? "0":"")+ to_string(hh);
            time = hour + ":" + mm + ":" + ss;
        }
        return time;
    }
    
  • + 0 comments

    s=input().split(':')

    print(s)

    if 'PM' in s[2]: s[2]=s[2][:2] if s[0]!='12': s[0]=int(s[0])+12 print(f'{s[0]}:{s[1]}:{s[2]}') elif 'AM' in s[2]: s[2]=s[2][:2] if s[0]=='12': s[0]='00' print(f'{s[0]}:{s[1]}:{s[2]}')

  • + 0 comments

    Java Solution

    public static String timeConversion(String s) {
            boolean isAM = false;
            
            if (s.endsWith("AM")) {
                isAM = true;
            }
            
            s = s.substring(0, s.length() - 2);
            int hour = Integer.valueOf(s.substring(0,2));
            
            if (isAM && hour == 12) {
                return "00".concat(s.substring(2));
            } else if (!isAM && hour != 12) {
                return Integer.toString(hour + 12).concat(s.substring(2));
            } else {
                return s;
            }
        }
    
  • + 0 comments
    # Write your code here
        s = s.split(":")
        hours = int(s[0])
        minutes = int(s[1])
        seconds = int(s[2][:2])
        am_pm = s[2][2:]
        
        if am_pm == "PM":
            if hours >= 1:
                hours = hours + 12
        elif am_pm == "AM":
            if hours >= 12:
                hours = hours - 12
        hours = "{:02}".format(hours)
        minutes = "{:02}".format(minutes)
        seconds = "{:02}".format(seconds)
        return f"{hours}:{minutes}:{seconds}"