C# 如何比较日期时间的时间部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10290187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare time part of datetime
提问by Developer
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"?
如何在C#中比较它并说出哪个时间是“晚于”?
采纳答案by Justin Pihony
回答by mgnoonan
Use the DateTime.Comparemethod:
使用的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);
Edit:If you just want to compare the times, and ignore the date, you can use the TimeOfDayas others have suggested. If you need something less fine grained, you can also use the Hourand Minuteproperties.
编辑:如果您只想比较时间,而忽略日期,您可以TimeOfDay按照其他人的建议使用。如果您需要不那么细粒度的东西,您还可以使用Hour和Minute属性。
回答by kaveman
The <, <=, >, >=, ==operators all work directly on DateTimeand TimeSpanobjects. So something like this works:
的<,<=,>,>=,==运营商都直接工作在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
}

