Compare time in HH:MM format in C#

Niladri.biswas
Posted by Niladri.biswas under C# category on | Points: 40 | Views : 9181
Solution1:

public int CompareTime(string t1, string t2)
{

int i = -1;

int hr1 = Convert.ToInt32(t1.Split(':')[0]);
int hr2 = Convert.ToInt32(t2.Split(':')[0]);

int min1 = Convert.ToInt32(t1.Split(':')[1]);
int min2 = Convert.ToInt32(t2.Split(':')[1]);

if (hr2 == hr1)
{
if (min2 == min1)
{
i = 0;
}
if (min2 > min1)
{
i = 1;
}
}
if (hr2 > hr1)
{
i = 1;
}

return i;
}


Solution 2:

public int CompareTime(string t1, string t2)
{
TimeSpan s1 = TimeSpan.Parse(t1);
TimeSpan s2 = TimeSpan.Parse(t2);
return s2.CompareTo(s1);
}



How to Invoke

var t1 = DateTime.Now.ToString("HH:mm");
var t2 = "21:10";
var res = CompareTime(t1, t2);


Hope this helps

Comments or Responses

Login to post response