C#验证给定的字符串形式的日期是否合法的代码

把做工程过程中重要的内容做个记录,如下的资料是关于C#验证给定的字符串形式的日期是否合法的代码。

    public static bool IsDate(ref string date)
    {
        if (IsNullOrEmpty(date))
        {
            return true;
        }

        date = date.Trim();

        date = date.Replace(@"", "-");
        date = date.Replace(@"/", "-");

        if (date.IndexOf("今") != -1)
        {
            date = DateTime.Now.ToString();
        }

        try
        {
            date = Convert.ToDateTime(date).ToString("d");
            return true;
        }
        catch
        {
            if (!IsInt(date))
            {
                return false;
            }

            #region 对纯数字进行解析
            if (date.Length == 8)
            {
                string year = date.Substring(0, 4);
                string month = date.Substring(4, 2);
                string day = date.Substring(6, 2);

                if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
                {
                    return false;
                }
                if (Convert.ToInt32(month) > 12 || Convert.ToInt32(day) > 31)
                {
                    return false;
                }

                date = Convert.ToDateTime(year + "-" + month + "-" + day).ToString("d");
                return true;
            }

            if (date.Length == 6)
            {
                string year = date.Substring(0, 4);
                string month = date.Substring(4, 2);

                if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
                {
                    return false;
                }
                if (Convert.ToInt32(month) > 12)
                {
                    return false;
                }

                date = Convert.ToDateTime(year + "-" + month).ToString("d");
                return true;
            }

            if (date.Length == 5)
            {
                string year = date.Substring(0, 4);
                string month = date.Substring(4, 1);

                if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
                {
                    return false;
                }

                date = year + "-" + month;
                return true;
            }

            if (date.Length == 4)
            {
                string year = date.Substring(0, 4);

                if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
                {
                    return false;
                }

                date = Convert.ToDateTime(year).ToString("d");
                return true;
            }
            #endregion

            return false;
        }
    }
上一篇:cv2读出来的图片的颜色通道是bgr


下一篇:[spring-core]类型转换机制