Convert time from 24 hour clock to 12 hour clock format in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to convert time from 24 hour clock to 12 hour clock format.

For this we will be provided with certain time in 24 hour format. Our task is to convert it into 12 hour format with the extension of “AM” or “PM”.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//converting into 12 hour format
void convert_12hour(string str){
   int h1 = (int)str[0] - '0';
   int h2 = (int)str[1] - '0';
   int hh = h1 * 10 + h2;
   //finding the extension
   string Meridien;
   if (hh < 12) {
      Meridien = "AM";
   }
   else
      Meridien = "PM";
      hh %= 12;
   if (hh == 0) {
      cout << "12";
      for (int i = 2; i < 8; ++i) {
         cout << str[i];
      }
   } else {
      cout << hh;
      for (int i = 2; i < 8; ++i) {
         cout << str[i];
      }
   }
   cout << " " << Meridien << '\n';
}
int main(){
   string str = "17:35:20";
   convert_12hour(str);
   return 0;
}

Output

5:35:20 PM
raja
Published on 22-Jan-2020 12:16:56
Advertisements