C# and multicultural IsDate() and ToDate()

C# does not provide IsDate() function. Sometimes in your developer environment region settings are different from the live environment. In my case, I don’t know what region settings there are in my company servers.

For this reason, I created a function to check is a string is a date in a culture and to convert a string to a date.

/// 
/// Determines whether the specified text is date.
/// 
/// The text.
/// 
/// true if the specified text is date; 
/// otherwise, false.
/// 
public static bool IsDate(this string text)
{
    if (!string.IsNullOrEmpty(text))
    {
        DateTime result = DateTime.MinValue;
        foreach (CultureInfo cultureInfo in 
                 CultureInfo.GetCultures(CultureTypes.AllCultures))
        {
            try
            {
                if (DateTime.TryParse(text, cultureInfo, 
                                      DateTimeStyles.None, 
                                      out result))
                    return true;
            }
            catch (Exception ex) { }
        }
    }

    return false;
}

/// 
/// To the date.
/// 
/// The text.
/// System.Nullable<DateTime>.
public static DateTime? ToDate(this string text)
{
    if (!string.IsNullOrEmpty(text))
    {
        DateTime result = DateTime.MinValue;
        foreach (CultureInfo cultureInfo in 
                 CultureInfo.GetCultures(CultureTypes.AllCultures))
        {
            try
            {
                if (DateTime.TryParse(text, cultureInfo, 
                                      DateTimeStyles.None, 
                                      out result))
                    return result;
            }
            catch (Exception ex) { }
        }
    }

    return null;
}

Happy coding!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.