如何比较C#中的DateTime?

Ash*_*shu 120 .net c# datetime

我不希望用户给出返回日期或时间.

如何比较输入的日期和时间是否低于当前时间?

如果当前日期和时间是2010年6月17日,下午12:25,我希望用户不能在2010年6月17日之前和下午12:25之前给出日期.

如果用户输入的时间是2010年6月16日和下午12:24,我的函数返回false

MuS*_*aNG 282

微软还实现了运营商的''和'>'.所以你用这些来比较两个日期.

if (date1 < DateTime.Now)
   Console.WriteLine("Less than the current time!");
Run Code Online (Sandbox Code Playgroud)

  • 来源MSDN; 这些被记录为DateTime Operators笨拙地标记为"DateTime.Greater than","DateTime.LessThanOrEqualTo"..... https://msdn.microsoft.com/en-us/library/ff986512%28v=vs.90% 29.aspx (6认同)
  • 这不是完整的答案。当将DateTime Kind设为ocnsideration时,它应该是`date1.ToLocalTime()&lt;DateTime.Now`或`date1.ToUniversalTime()&lt;DateTime.UtcNow`。 (3认同)
  • 我正在使用 Unity 2017 并使用此运算符对列表进行排序会给我错误的结果。我什至试图直接比较 DateTime.ticks,但也失败了。我不得不使用 DateTime.CompareTo 来获得正确的结果,但我不知道为什么。 (2认同)
  • 错了 这无法以正确的方式比较UTC和本地时间。 (2认同)

Ahm*_*ıcı 162

MSDN: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);
// The example displays the following output:
//    8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM
Run Code Online (Sandbox Code Playgroud)

  • 您的答案提供了一种方法来查看差异,而不仅仅是知道日期是在之前还是之后.当然,对于OP来说,他的答案会更好,但是对于那些从谷歌来到这里的人来说,你的答案会更好(包括自我). (2认同)
  • 我发现您的答案很有价值,因为我正在查看使用该代码的一些旧代码 (2认同)

Sна*_*ƒаӽ 20

MuSTaNG的答案说明了一切,但我仍然在添加它以使其更精细,链接和所有.


传统的运营商

DateTime自.NET Framework 1.1起可用.而且,加法和减法DateTime的对象也是可能的使用常规的运营商+-.

MSDN的一个例子:

平等:
System.DateTime april19 = new DateTime(2001, 4, 19);
System.DateTime otherDate = new DateTime(1991, 6, 5);

// areEqual gets false.
bool areEqual = april19 == otherDate;

otherDate = new DateTime(2001, 4, 19);
// areEqual gets true.
areEqual = april19 == otherDate;
Run Code Online (Sandbox Code Playgroud)

其他操作员也可以使用.

以下是所有可用运营商的列表DateTime.


小智 10

如果您有两个看起来相同的 DateTime,但比较或等于没有返回您期望的结果,则可以按以下方法比较它们。

这是一个精度为 1 毫秒的示例:

bool areSame = (date1 - date2) > TimeSpan.FromMilliseconds(1d);
Run Code Online (Sandbox Code Playgroud)


Alb*_*rtK 6

在一般情况下,您需要DateTimes与相同的进行比较Kind

if (date1.ToUniversalTime() < date2.ToUniversalTime())
    Console.WriteLine("date1 is earlier than date2");
Run Code Online (Sandbox Code Playgroud)

从解释MSDNDateTime.Compare(这也是相关的运营商一样><==等):

为了确定 t1 到 t2 的关系,Compare 方法比较了 t1 和 t2 的 Ticks 属性,但忽略了它们的 Kind 属性。在比较 DateTime 对象之前,请确保这些对象表示同一时区的时间。

因此,在处理以DateTimes不同时区表示的内容时,简单的比较可能会产生意想不到的结果。