Friday, January 3, 2014

DateTime data checking and returning as given format to stop any run time error

In C# code generally we use Convert.ToDateTime() function to convert our desired value to datetime object but at run time we faced different scenarios where value can be null or if value is null then we need to return null instead of datetime.minvalue [when trying to convert null to datetime then this value will return], and in some cases we need specific formatted string to show datetime value or when trying to insert data in database, for those scenarios following method is a generic approach to convert datetime value to string without any error and return a desired value with  a desired format.

public static string GetDatetimeAsString(object value, string defaultValue = null, string format = "MM/dd/yyyy hh:mm tt")
        {
            string resultStr = "";
            DateTime result = new DateTime();
            string passedVal = GetString(value);
            if (passedVal == "")
            {
                resultStr = defaultValue;
            }
            else if (passedVal.Length > 0)
            {
                DateTime.TryParse(passedVal, out result);

                resultStr = result.ToString(format);
            }

            return resultStr;
        }

//this is to check string data and return proper value to stop runtime error
 public static string GetString(object value)
        {
            string result = "";

            if (value != null && value != DBNull.Value)
                result = value.ToString();

            return result;
        }

No comments:

Post a Comment