如何比较日期时间的时间部分
假设我们有
DateTime t1 = DateTime.Parse("2012/12/12 15:00:00.000");
和
DateTime t2 = DateTime.Parse("2012/12/12 15:03:00.000");
如何在C#中比较它并说出哪个时间“晚于”?
您可以使用TimeOfDay属性并使用Compare对它。
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.
<
, <=
, >
, >=
, ==
运算符都直接在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 }
使用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
属性。