假设我们有
DateTime t1 = DateTime.Parse("2012/12/12 15:00:00.000");
和
DateTime t2 = DateTime.Parse("2012/12/12 15:03:00.000");
如何在C#中比较它并说出哪个时间“晚于”?
答案 0 :(得分:65)
TimeSpan.Compare(t1.TimeOfDay, t2.TimeOfDay)
根据文件:
-1 if t1 is shorter than t2.
0 if t1 is equal to t2.
1 if t1 is longer than t2.
答案 1 :(得分:20)
<
,<=
,>
,>=
,==
运算符直接在DateTime
和TimeSpan
个对象上运行。所以这样的事情有效:
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
}
答案 2 :(得分:2)
使用the DateTime.Compare
方法:
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);
修改:如果您只想比较时间并忽略日期,可以像其他人建议的那样使用TimeOfDay
。如果您需要不太精细的内容,您还可以使用Hour
和Minute
属性。