Time Conversion

  • + 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
        }
    }
    

    }