Time Conversion

  • + 0 comments

    c++20 (chose readability over latency)

    string timeConversion(string s) {
    
    int nDigits = 2;
    
    auto time = s.substr(0, s.size() - nDigits);
    auto zone = s.substr(s.size() - nDigits);
    int hour = stoi(time.substr(0, nDigits));
    
    std::stringstream ss;
    ss << std::setw(nDigits) << std::setfill('0');
        
    if(zone == "AM"){
        auto amHour = hour%12;
    
        ss << amHour << time.substr(nDigits);
    }
    else{
        
        auto pmHour = hour;
        
        if(hour < 12){
            pmHour = hour + 12;
        }
    
        ss << pmHour << time.substr(nDigits);
    }
    
    return ss.str();
    }