Time Conversion code in C#

Problem source: https://www.hackerrank.com/challenges/time-conversion

You are given time in AM/PM format. Convert this into a 24 hour format.

Note Midnight is 12:00:00AM or 00:00:00 and 12 Noon is 12:00:00.

Input Format

Input consists of time in the AM/PM format i.e. hh:mm:ssAM or hh:mm:ssPM
where
01hh12
00mm59
00ss59

Output Format

You need to print the time in 24 hour format i.e. hh:mm:ss
where
00hh23
00mm59
00ss59

Sample Input

07:05:45PM

Sample Output

19:05:45

class Time_Conversion_Hackerrank
{
static void Main(string[] args)
{
string strTime = Console.ReadLine();
string[] timeArr = strTime.Split(‘:’);
string AMPM = timeArr[2].Substring(2);
if (AMPM.Contains(“PM”))
{
string hh = string.Empty;
if (timeArr[0] == “12”)
{
hh = “12”;
}
else if (Convert.ToInt16(timeArr[0]) + 12 == 24)
{
hh = “00”;
}
else
{
hh = (Convert.ToInt16(timeArr[0]) + 12).ToString();
}

Console.WriteLine(string.Concat(hh, “:”, timeArr[1], “:”, timeArr[2].Substring(0, 2)));
}
else if (AMPM.Contains(“AM”))
{
if (timeArr[0] == “12”)
{
Console.WriteLine(string.Concat(“00:”, timeArr[1], “:”, timeArr[2].Substring(0, 2)));
}
else
{
Console.WriteLine(strTime.Substring(0, strTime.Length – 2));
}
}
Console.ReadKey(true);
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s