Thursday, May 17, 2012

Checking Valid date or not using C#

In this post I am going to explain about how to check the given string is valid date or not.For VB.NET we have the predefined function called “ISDATE()” however for the C# we don’t have any predefined function to check the given string is valid or not.So in this post I am going to Explain given string is valid or not.
To do this Create an console application and copy the following code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
           string s1 = "29-FEB-20112";
           IsDate(s1);
        }

        public static void IsDate(string s1)
        {
            bool bSuccess = false;
            DateTime d1;
          
            bSuccess = DateTime.TryParse(s1, out d1);
            if (bSuccess == true)
            {
                Console.WriteLine(d1.ToString());
               

            }
            else
            {
                Console.WriteLine("Not a date at all");
            }
            Console.Read();
        }
    }
}


If you observe the above program I have used the DateTime.TryParse(). It Converts the specified string representation of a date and time to its Datetime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded. It takes Two Argument one is string which need to convert.Second one is the out varable of Datetime.If the conversion is success the date will store in the out varaible and returns true else returns false.

Output: 


No comments:

Post a Comment