How to compare time part of datetime

醉酒当歌 提交于 2019-11-27 20:25:49

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.
kaveman

The <, <=, >, >=, == operators all work directly on DateTime and TimeSpan objects. So something like this works:

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

if(t1.TimeOfDay > t2.TimeOfDay) {
    //something
}
else {
    //something else
}

Use the DateTime.Compare method:

DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

Console.WriteLine("{0} {1} {2}", date1, relationship, date2);

Edit: If you just want to compare the times, and ignore the date, you can use the TimeOfDay as others have suggested. If you need something less fine grained, you can also use the Hour and Minute properties.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!