Introduction
This blog will discuss how to write a Program to convert 24 hour time to 12 hour time.
We are given a time in 24-hour format and we need to convert it into 12-hour format.
Example:
Input
20:25:30
Output:
8:25:30
In 24 hour time, after 12 noon, 13:00 is said to be 1p.m similarly 14:00 as 2 pm and so on.
You can also read about dynamic array in c.
Also see: C Static Function
Approach
The approach to write a Program to convert 24 hour time to 12 hour time is to first get hours, then calculate whether the time is in AM or PM. We need to calculate whether the time is from 0 to 12 or from 12 to 24. Both the cases should be handled separately and then displayed.
Time Complexity for writing a program to convert 24 hour time to 12-hour time = O(1), since constant time is taken.
Till now, I assume you must have got the basic idea of what has been asked in the problem statement. So, I strongly recommend you first give it a try.
PseudoCode
___________________________________________________________________
procedure convert(string str):
___________________________________________________________________
1. h1 = (int)str[0] - '0'
2. h2 = (int)str[1] - '0'
3. hh = h1 * 10 + h2
4. if (hh < 12):
Meridien = "AM"
else
Meridien = "PM";
5. hh %= 12
6. if (hh == 0):
cout << "12"
for (i = 2 to 8):
cout << str[i]
7. else
cout << hh
for (i = 2 to 8):
cout << str[i]
8. Print meridien
end procedure
___________________________________________________________________
Also read, Tribonacci Series
Implementation in C++
#include <bits/stdc++.h>
using namespace std;
// Function to convert 24-hour time to 12 hour
void convert(string str)
{
// Getting Hours
int h1 = (int)str[0] - '0';
int h2 = (int)str[1] - '0';
int hh = h1 * 10 + h2;
// Finding out AM or PM
string Meridien;
if (hh < 12) {
Meridien = "AM";
}
else
Meridien = "PM";
hh %= 12;
// Handling 00 and 12 case separately
if (hh == 0) {
cout << "12";
// Printing minutes and seconds
for (int i = 2; i < 8; ++i) {
cout << str[i];
}
}
else {
cout << hh;
// Printing minutes and seconds
for (int i = 2; i < 8; ++i) {
cout << str[i];
}
}
// After time print am or pm
cout << " " << Meridien << '\n';
}
int main()
{
// enter in 24 hour format
string str;
cin>>str;
convert(str);
return 0;
}
Output:
Sample Input:
20:25:30
Sample Output:
8:25:30 PM
You can implement code by yourself with the help of the online c compiler.
Complexity Analysis
Time Complexity: O(1), The constant time is taken to convert time from 24-hour format to 12-hour format.
Space complexity: O(1), since no extra variable was used.
Also see, Short int in C Programming