12 Hour Time to 24 Hour Time in C | Program

Today I wrote a program that converts a time that is given in 12 hour time to 24 hour time/military time. Overall it’s pretty simple. It takes an input from the user and stores a variable for hours, minutes, and pm/am. Then if it is pm it adds 12 to the hours variable. Then, at the end it prints hours and minutes in the proper format and if hours is less than 10 it adds a leading zero.

//This program will convert AM/PM time to 24 hour time

#include <stdio.h> //adds the necessary library
	int main(void){ //creates the main function
	int h, m; // initializes an int variable for hours and minutes
	char ampm; // initializes a char variable that will be used to determine am or pm

	printf("This program will convert 12 hour time to 24 hour time\nPlease enter a time in the format hour:minute AM/PM for example 9:15 PM\n"); //Explains the program and prompts the user to enter a time
	scanf("%d:%d %cm", &h, &m, &ampm); //takes input from the user and stores each input into its respective variable

	if(ampm == 'P' || ampm == 'p'){ // checks if the time given is pm. It is not case sensitive
		h += 12;	// if the time is pm then it will add 12 to the time
	}

	printf("The time is %d:%d", h, m); // prints the new time

	return 0; // reports that the main function was completed successfully
}

/*
Output:
This program will convert 12 hour time to 24 hour time
Please enter a time in the format hour:minute AM/PM for example 9:15 PM
11:45 pm (The user entered 11:45 pm)
The time is 23:45
*/