Sponsored Ad

Wednesday, August 18, 2010

How to Handle string to date conversion error in C#

Sometime while coding, programmers forget to check for valid date type exception and they directly use the date string to convert it while there is ways by which you can check for valid date sting and avoid the unwanted exception.

1. Check for null string
2. Keep conversion logic in try catch block
3. if date variable is object then check for null also

How to Handle string to date conversion error in C#

 

using System;
using System.Text;
using System.Collections;
using System.Data;
namespace Console_App
{
    public class DateConversion
    {
        public static void Main()
        {
            string strDate1 = "", strDate2 = "10/10/2010";
            object obj1=null, obj2 = "10/10/2010";

            try
            {
                if(strDate1 != "")
                Console.WriteLine("string to DateConversion conversion: " + Convert.ToDateTime(strDate1));
            if (strDate2 != "")
                Console.WriteLine("string to DateConversion conversion: " + Convert.ToDateTime(strDate2));

            if (obj1 != null && obj1 != "")
                Console.WriteLine("string to DateConversion conversion: " + Convert.ToDateTime(obj1));
            if (obj2 != null && obj2 != "")
                Console.WriteLine("string to DateConversion conversion: " + Convert.ToDateTime(obj2));
            }
            catch(Exception ex)
            {
                //handle exception here
            }
            Console.ReadLine();           
        }
    }
}

0 comments:

Post a Comment

Sponsored Ad

More Related Articles

Website Update

Followers