DateTimeUtils Class: IsDate

Search

 by Remas Wojciechowski

July 4th, 2001

In this article we will develop a method for checking if a given string represents a valid date/time value.

Most of you will be familiar with the VB(Script) function IsDate. Let's us try and implement the functionality in .NET.

The DateTime structure is used in .NET to represent dates and times. One of its methods is Parse. That method is used to converts a specified String representation of a date and time to its DateTime equivalent. If the given string cannot be converted, the method throws an exception of type FormatException.

The idea is to use this method upon the string we want to validate. If the method fails and the exception thrown is of type FormatException then our method should return false. Otherwise it returns true. We will implement the IsDate method as a static (c#) / shared (vb.net) one so it's not necessary to instantiate the DateTimeUtils class.

Here is the code:

DateTimeUtils.IsDate in C#
class DateTimeUtils {

  public static bool IsDate(string strDate) {
    DateTime dtDate;
    bool bValid = true;
    try {
      dtDate = DateTime.Parse(strDate);
    }
    catch (FormatException eFormatException) {
      // the Parse method failed => the string strDate cannot be converted to a date.
      bValid = false;
    }
    return bValid;
  }

}
DateTimeUtils.IsDate in VB.NET
Class DateTimeUtils

  Public Shared Function IsDate(ByVal strDate As String) As Boolean
    Dim dtDate As DateTime
    Dim bValid As Boolean = True
    Try
      dtDate = DateTime.Parse(strDate)
    Catch eFormatException As FormatException
      ' the Parse method failed => the string strDate cannot be converted to a date.
      bValid = False
    End Try
    Return bValid
  End Function
End Class

Have fun!