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.

The input is,

int twenty_four_hrs;
cin>>twenty_four_hrs;

In the above code, the input variable is twenty_four_hrs. Then the variables hrs and min are declared as integer as time belongs to integer datatype.

How to separate hours and minutes?

int hrs=twenty_four_hrs/100;
int min=twenty_four_hrs%100;

On dividing the input time by 100, we will get the hours which is stored in the variable name called hrs.

The same way the minutes on doing, twenty_four_hrs%100, we can get the minutes which is stored into the variable name called min.

Conditions:

if(hrs==0&&hrs!=12){
hrs=12;
}
else if(hrs==12&&hrs!=0){
hrs=12;
}
else if(hrs<12&&hrs!=0){
hrs=hrs;
min=min;
}
else if(hrs>12&&hrs!=0){
hrs=hrs-12;
min=min;
}

In the above code,

  • if condition checks, hrs is equal to 00 and hrs not equal to 12 (i.e)00 is nothing but 12 .
  • else if condition checks whether hrs is equal to 12 and hrs not equal to 0 then hrs remains with the same 12 denoted in PM.
  • else if hrs less than 12 and hrs not equal to 0 then both the hrs and min remains the same.
  • if hrs greater 12 and hrs not equal to 0 then hrs=hrs-12 , min remains the same.

INPUT:

1245

C++ program to convert 24 hour format to 12 hour format

#include<iostream.h>
#include<cstdio.h>
using namespace std;
int main(){
int twenty_four_hrs;
cout<<"Enter the time in twenty four hour format:";
cin>>twenty_four_hrs;
cout<<"\n";
int hrs,min;
hrs=twenty_four_hrs/100;
min=twenty_four_hrs%100;
cout<<"Time in Twelve Hour Format is:\t";
if(hrs==0&&hrs!=12){
    hrs=12; 
    printf("%.2d:%.2d AM\n",hrs,min);
 }
else if(hrs==12&&hrs!=0){
    hrs=12; 
    printf("%.2d:%.2d PM\n",hrs,min);
 }
else if(hrs<12&&hrs!=0){
    hrs=hrs;
    min=min; 
    printf("%.2d:%.2d AM\n",hrs,min);
 }
else if(hrs>12&&hrs!=0)
 { 
    hrs=hrs-12; 
    min=min; 
    printf("%.2d:%.2d PM\n",hrs,min);
 }
}

When the input is 1245 the hrs=1245/100 becomes 12 and min=0045%100 becomes 45 and from the given conditions.

Then hrs is compared on checking it enters the second else if statement where the hrs and minute remains the same and the output is,

Thus the program coverts from 24 to 12 hour format.

OUTPUT:

12:45 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 *