Convert 24 hour format to 12 hour format in C++

In this tutorial, we are going to learn how to Convert 24 hour format to 12 hour format in C++.

This program converts 24 to 12 hour format.

How to Input the clock format in C++

The time should be inĀ  HH:MM:SS where HH denotes Hours, MM denotes Minutes and SS is Seconds.

How to use AM/PM notation?

  • We denote 00:00 as 00:00 AM
  • 12:00 as 12:00 PM
  • 23:00 as 23:00 PM

In this 24 to 12 hour conversion, the hour value is changed and not the minute value.

#include <iostream>
#include <iomanip>

using namespace std;

void convertTo12HourFormat(int hour, int minute) {
    string period = (hour < 12) ? "AM" : "PM";

    if (hour == 0) {
        hour = 12;
    } else if (hour > 12) {
        hour -= 12;
    }

    cout << setw(2) << setfill('0') << hour << ":" << setw(2) << setfill('0') << minute << " " << period << endl;
}

int main() {
    int hour24, minute;

    cout << "Enter time in 24-hour format (HH:MM): ";
    cin >> hour24;
    cin.ignore(); // ignore the ':' character
    cin >> minute;

    convertTo12HourFormat(hour24, minute);

    return 0;
}

Output:

Enter time in 24-hour format (HH:MM): 23:11
11:11 PM

We hope this tutorial helped you to understand how to convert 24 hour format to 12 hour format in C++.

Also, read:

Leave a Reply

Your email address will not be published. Required fields are marked *