Home » C Program to convert 24 Hour time to 12 Hour time

C Program to convert 24 Hour time to 12 Hour time

by Online Tutorials Library

C Program to convert 24 Hour time to 12 Hour time

In this tutorial, we will write a program that will convert a given time of 24-hour format to a 12-hour format.

The time will be given in the format of – Hours: Minutes: Seconds

For example –

Input : 20:35:20

Output : 8:35:20 PM

Input : 00:15:40

Output : 12:15:40 AM

Algorithm

The midnight in 24-hour clock format is 00:00:00 and in 12-hour format is 12:00:00. Now we need to observe that the minutes and seconds in both the observations are the same. There is a change in hours only when there is a change in the meridian.

To check hours we will first convert the input string of hours into an integer. After changing it into integer we will modulo the hour with 12 and that will be in the 12-hour format.

The case when there is 00 in the hour will be calculated as a separate case.

C code Implementation

Output:

C Program to convert 24 Hour time to 12 Hour time

Code Explanation

  • Take the char str into the function.
  • Obtain the first digit and second digit of the hour from the 24-hour format string. The ‘0’ converts the string value to an integer.
  • As we have got individual digit of hour we will convert into a number.
  • Check if the hh is in 12 hour or 24 hour format using if-else and set the Meridian as AM or PM.
  • Modulo hh with 12 and convert the time into 12-hour format.
  • We will handle the 00 in 24-hour separately as it is the same as 12 in 12-hour format.
  • After printing the hour print the minutes and seconds
  • Print the minutes and seconds if it is not the 00 case
  • Print the meridian of 12-hour format.

You may also like