比较特定格式的两个 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/