C# 检查 DateTime 是否在 DateTime.Now 之前
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17933697/
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
Checking if a DateTime is before DateTime.Now
提问by Newbie
How can I check using some form of if
statement if a certain DateTime
, (say in this case called dateAndTime1) is before the current date and time, which I presume will be retrieved using DateTime.Now
?
if
如果某个DateTime
,(在这种情况下称为 dateAndTime1)在当前日期和时间之前(我认为将使用 检索),我如何使用某种形式的语句进行检查DateTime.Now
?
采纳答案by Jim
if(dateAndTime1 < DateTime.Now)
{
//do something
}
回答by welegan
the <, <=, >, >= and == operators work on DateTime instances, so
<、<=、>、>= 和 == 运算符适用于 DateTime 实例,因此
if(dateAndTime1 < DateTime.Now)
if(dateAndTime1 < DateTime.Now)
Note that if you are comparing this in a loop, some small efficiency can be gained by setting DateTime now = DateTime.Now
before the loop and comparing against now
请注意,如果您在循环中进行比较,则可以通过DateTime now = DateTime.Now
在循环前进行设置并与now
回答by Chase Florell
Inline works too.
内联也有效。
// bool variable
bool isHistory = dateAndTime1 < DateTime.Now;
// string return statement
return dateAndTime1 < DateTime.Now ? "History" : "Future";