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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:12:12  来源:igfitidea点击:

How to compare time part of datetime

c#.netdatetimecompare

提问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

You can use the TimeOfDayproperty and use the Compareagainst it.

您可以使用TimeOfDay属性并对其使用比较

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.

回答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按照其他人的建议使用。如果您需要不那么细粒度的东西,您还可以使用HourMinute属性。

回答by kaveman

The <, <=, >, >=, ==operators all work directly on DateTimeand TimeSpanobjects. So something like this works:

<<=>>===运营商都直接工作在DateTimeTimeSpan对象。所以像这样的工作:

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
}