SIGN UP MEMBER LOGIN:    
ARTICLE

Easy Date Validation in C#

Posted by Scott Lysle Articles | C# Language February 23, 2009
This article describes a simple approach to validating dates received as strings (e.g., 2/21/2008).
Reader Level:

Introduction

This article describes a simple approach to validating dates received as strings (e.g., 2/21/2008). It requires on a few lines of code but will confirm that the date provided as a string is an actual date. The formats for the date string used in this example conform to the US standard of MM/DD/YYYY but that can easily be modified to work with other UI cultures. The method shown may be of use if you have an application that receives dates as strings rather than as actual DateTime values.



Figure 1: Test Application in Use

The Code

The code is very simple and does not require much of an explanation. All that is done is to split the date string up into month, day, and year, and then to attempt to create a date time value from those parts. If the operation succeeds, the method returns true, if it fails (with an invalid date) the failure is trapped in a catch block which in turn returns a false. The sum total of the operation is as follows:

        /// <summary>
        /// Determine if Date String is an actual date
        /// Date format = MM/DD/YYYY
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        private bool ValidateDate(string date)
        {
            try
            {
                // for US, alter to suit if splitting on hyphen, comma, etc.
                string[] dateParts = date.Split('/');

                // create new date from the parts; if this does not fail
                // the method will return true and the date is valid
                DateTime testDate = new
                    DateTime(Convert.ToInt32(dateParts[2]),
                    Convert.ToInt32(dateParts[0]),
                    Convert.ToInt32(dateParts[1]));

                 return true;
            }
            catch
            {
                // if a test date cannot be created, the
                // method will return false
                return false;
            }
        }

Login to add your contents and source code to this article
share this article :
post comment
 

Thanks a lot...great useful post :))

Posted by Sunny Kumar Aug 31, 2011

This datetime parser is excellent. I really enjoyed. Perfect code. Thanks a lot!

Posted by kilambi ramanujam Feb 20, 2010

Strings.FormatDateTime is not part of C#, it can be made available to your application if you want to roll in the Microsoft.VisualBasic (legacy VB6) namespace; not something I would recommend.

Posted by Scott Lysle Mar 12, 2009

{
    try {
        Strings.FormatDateTime(DateString, DateFormat.GeneralDate);
        Interaction.MsgBox("Valid Date");
    }
    catch (Exception ex) {
        Interaction.MsgBox("Invalid Date");
    }
}

 This is already a part of C# and works pretty well. Less code and more speed.

Posted by James Mouchett Mar 12, 2009
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor