c# - 将 DateTime 与触发代码进行比较的最佳方法

标签 c# asp.net-mvc datetime

比较特定格式的两个 DateTime 并在 DateTime 已过时触发代码的最佳方法是什么。

我的日期时间格式为 4/26/2017 10:00:00 AM

    DateTime currentDateTime = DateTime.Now;
    DateTime eventDateTime = DateTime.Parse("4/26/2017 10:00:00 AM");

int result = DateTime.Compare(currentDateTime, eventDateTime);

if (result < 0)
    Response.Write( "is earlier than Do Nothing");
else if (result == 0)
    Response.Write("is the same time as: Do Nothing");         
else
    Response.Write("Time is greater, Trigger Action ");

上面的代码是否可以进行比较,或者我们可以改进它。

最佳答案

在我看来,您建议的方法是在 C# 中比较 2 个 DateTime 变量的最有效和可接受的方法,考虑到如果这 2 个日期也相等则您需要采取行动。

旁注:

如果你只需要比较2个DateTime没有相等的条件,你可以这样写:

if (currentDateTime < eventDateTime)
    Response.Write("is earlier than Do Nothing");
else
    Response.Write("Time is greater, Trigger Action");   

它更清洁、更高效。

关于c# - 将 DateTime 与触发代码进行比较的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43601465/

相关文章:

asp.net-mvc - ASP.NET MVC 项目架构

javascript - 使用 Javascript 检查日期是否为给定格式

c# - 如何防止ServiceStack EventLogFactory记录DEBUG事件?

c# - WPF ListView 中的 DateTime 区域特定格式

c# - 是否可以记录程序执行期间抛出的所有异常?

c# - 拖动箭头断点时调试范围内的错误

asp.net-mvc - 防止更改隐藏字段

asp.net - 从 Web API 之外的 ActionFilter 或 ASP.NET MVC Web Controller 获取 HttpRequestMessage

javascript - float 日期条形图对齐歪斜

.net - 如何在 NodaTime 中获取 "start of the year/month"?