Sunday, August 22, 2010

Extension method: DateTime.IsInFuture()

In this post you can find a simple DateTime extension method. The IsInFuture method simply returns a boolean indicating whether the DateTime instance is in the future or not.

   1:  public static class DateTimeExtensions
   2:  {
   3:      public static bool IsInFuture(this DateTime dateTime)
   4:      {
   5:          int compareResult = DateTime.Compare(dateTime, DateTime.Now);
   6:   
   7:          return compareResult != -1;
   8:      }
   9:  }

You can use it like this..

   1:  DateTime dateTimeInPast = new DateTime(2010, 5, 20);
   2:  DateTime dateTimeInFuture = new DateTime(2025, 11, 20);
   3:   
   4:  Console.WriteLine(dateTimeInPast.IsInFuture()); //Prints False
   5:  Console.WriteLine(dateTimeInFuture.IsInFuture()); //Prints True

3 comments:

  1. what's wrong with "return dateTime > DateTime.Now;"

    ReplyDelete
  2. Thanks for your comment.

    Nothing is wrong with dateTime > DateTime.Now. I even think it might be a bit faster.

    ReplyDelete
  3. A remark made by James Curran. As implemented DateTime.Now.IsInFuture() returns true. To fix this change return compareResult != -1 to compareResult > 0;

    ReplyDelete