How to compare time part of datetime

DmitryBoyko picture DmitryBoyko · Apr 24, 2012 · Viewed 88.3k times · Source

Let's say we have

DateTime t1 = DateTime.Parse("2012/12/12 15:00:00.000");

and

DateTime t2 = DateTime.Parse("2012/12/12 15:03:00.000");

How to compare it in C# and say which time is "is later than"?

Answer

Justin Pihony picture Justin Pihony · Apr 24, 2012

You can use the TimeOfDay property and use the Compare against it.

TimeSpan.Compare(t1.TimeOfDay, t2.TimeOfDay)

Per the documentation:

-1  if  t1 is shorter than t2.
0   if  t1 is equal to t2.
1   if  t1 is longer than t2.