C# Program to Convert 24 Hour Format to 12 Hour Format Time Full Project For Beginners

  • Post author:
  • Post category:c#
  • Post comments:0 Comments

 

 

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);

}
}

Leave a Reply