tags:

views:

227

answers:

4

I know this is probably a pretty simple question, but i am trying to write a function that returns a bool value of "true" if a date passed is in the future, like this:

bool IsFutureDate(System.DateTime refDate)
{
    if (refDate > DateTime.Now)  // This doesn't seem to work
        return true;
    return false;
}

Anyone tell me who to write a function like this that actually works?

Thanks

+3  A: 

DateTime handling is always tricky.

I have summarized what's been mentioned so far and made this post Community Wiki.

Time Zone Handling

static bool IsFutureDateTime(DateTime dateTime) {
   // NOTE: ToUniversalTime() treats DateTimeKind.Unspecified as local time. We
   //       therefore insist that the input kind is always specified.
   if (dateTime.Kind == DateTimeKind.Unspecified) {
       string msg = "dateTime.Kind must not be DateTimeKind.Unspecified.";
       throw new ArgumentException(msg, "dateTime");
   }

   return dateTime.ToUniversalTime() > DateTime.UtcNow;
}

Comparing Dates Only

static bool IsFutureDate(DateTime date) {
    return date.Date > DateTime.Today;
}
Nick Guerrera
+5  A: 

The only thing I can think of is you might get undefined behaviour if refDate == today.

DateTime.Now includes the time. If refDate if for say today at 3:00 and you run it at 2:00 it will return true. If you run at 4:00 it will return false.

Compare it to DateTime.Today and that will just return the date, preventing the time of day influencing it.

Other than that it should all be fine..

Mongus Pong
Note that DateTime.Today has a time of 12 AM (00:00). Comparing a date that's sometime today against that will say it's in the future. If you want to check if the date portion is in the future, you could use: refDate.Date > DateTime.Today
TrueWill
A: 
bool IsFutureDate(DateTime refDate) {
    DateTime today = DateTime.Today;
    return (refDate.Date != today) && (refDate > today);
}
Jason
A: 

The TimeSpan structure is helpful:

http://msdn.microsoft.com/en-us/library/system.timespan.aspx

How precise do you need it to be? Down to the millisecond?

Kris Krause