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

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

Checking if a DateTime is before DateTime.Now

c#windows-phone-7datetimeif-statementwindows-phone-8

提问by Newbie

How can I check using some form of ifstatement 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.Nowbefore 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";