Time Conversion

  • + 0 comments

    //Language = C++ //Approach

    Extract the A or P from the given time string. A and P lies at second last index of string. string.size() - 2. Remove AM/PM from the given string.

    If the time is given in AM (Then only 12 AM will need to be addressed)

    If time is given in PM - Then there are two cases: i. When time is from 01 PM - 11 PM (Simply add 12 in the hrs) ii. When time is 12 PM (Skip this time as it is already in 24 hrs format)

    string timeConversion(string s) { int n = s.size(); bool isAM = (s.substr(n - 2, 1) == "A") ? true : false; s = s.substr(0, n-2);

    if(isAM){
        if(s[1] == '2'){
            s[0] = '0';
            s[1] = '0';
        }
    } else{
        //Time from 10 PM - 12 PM
        if(s[0] - '0'){
            //12 PM
            if(s[1] - '0' < 2){
                string hrs = to_string((s[1] - '0') + 10 + 12);
                s[0] = hrs[0];
                s[1] = hrs[1];
            }
        } else{
            //Time from 01 PM - 09 PM
            string hrs = to_string((s[1] - '0') + 12);
            s[0] = hrs[0];
            s[1] = hrs[1];
        }
    
    }
    return s.substr();
    

    }