C# Program to Convert 24 Hour Format to 12 Hour Format Time

First of all, I would like to thank them for searching my article. The reason for that is so many articles but thank you so much for reading my article. C# Program to Convert 24 Hour Format to 12 Hour Format Time We are going to know more about this very clearly through the article.

Midnight is 00:00:00 in the 24-hour clock format and 12:00:00 in the 12-hour format. We should now notice that the minutes and seconds in both observations are identical. The change in hours occurs only when there is a change in the meridian.

Firstly, set the 12 hr format date.

DateTime d = DateTime.Parse("05:00 PM");

Now let us convert it into the 24-hr format.

d.ToString("HH:mm"));
C# Program to Convert 24 Hour Format to 12 Hour Format Time

C# Program to Convert 24 Hour Format to 12 Hour Format Time

main.cs

// C# program to convert time from 24 hour
// to 12 hour format

using System;
// Convert Function which takes in
// 24hour time and convert it to
// 12 hour format
class GFG
{

static void convert12(string str)
{
// Get Hours
	int h1 = (int)str[0] - '0';
	int h2 = (int)str[1]- '0';

	int hh = h1 * 10 + h2;

	// Finding out the Meridien of time
	// ie. AM or PM
	string Meridien;
	if (hh < 12) {
		Meridien = "AM";
	}
	else
		Meridien = "PM";

	hh %= 12;

	// Handle 00 and 12 case separately
	if (hh == 0) {
		Console.Write("12");

		// Printing minutes and seconds
		for (int i = 2; i < 8; ++i) {
		Console.Write(str[i]);
		}
	}
	else {
		Console.Write(hh);
		// Printing minutes and seconds
		for (int i = 2; i < 8; ++i) {
		Console.Write(str[i]);
		}
	}

	// After time is printed
	// cout Meridien
Console.WriteLine(" "+Meridien);
}

//Driver code
public static void Main()
{

// 24 hour format
	string str = "17:35:20";
	convert12(str);

}
}

Execution of C# Program to Convert 24 Hour Format to 12 Hour Format Time

Initially, We have to declare the variables to store the input data. After running this program, A for loop and the if…else condition will help to convert the time format from 24 hours to 12 hours.

Raed Also:

Final Thoughts

C# Program to Convert 24 Hour Format to 12 Hour Format Time We hope you find this article very useful. And if you liked this article, we ask you to share it with your friends and help them too.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment