24

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?

Newbie
  • 1,134
  • 2
  • 10
  • 22
  • http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx .. is one way. As others have already pointed out, the usual comparison operators work too. – Robert Harvey Jul 29 '13 at 20:36
  • 6
    What's wrong with `if (dateAndTime1 < DateTime.Now)` ? Seems so overly obvious - I must be missing something! – marc_s Jul 29 '13 at 20:36

3 Answers3

53
if(dateAndTime1 < DateTime.Now)
{
  //do something
}
Jim
  • 6,337
  • 12
  • 39
  • 68
7

the <, <=, >, >= and == operators work on DateTime instances, so

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

welegan
  • 2,845
  • 2
  • 13
  • 20
  • 1
    per your note: you're right except on the edge case where it's a long running process and `now` always needs to be the immediate `DateTime.Now`. This is because when setting a `now` variable, it will be stale in long running processes... like I said though, "edge case", and probably rarely experienced. – Chase Florell Jul 29 '13 at 20:46
  • Actually specifically because of that I'd rather use a variable that is consistent throughout the loop. Obviously it depends on the use case, but I can imagine that when returning a certain set of values to the user, the anchor point should almost always be constant for a consistent result. – downhand Apr 20 '18 at 04:58
2

Inline works too.

// bool variable
bool isHistory = dateAndTime1 < DateTime.Now;

// string return statement
return dateAndTime1 < DateTime.Now ? "History" : "Future";
Chase Florell
  • 42,985
  • 56
  • 169
  • 364
  • 4
    Just for everyone's benefit, the name for the expression used in your example is a ternary expression. – Jim Jul 29 '13 at 20:57