如:201210  如何验证这样的年月组合,前面四位是年 ,后台两位是月。 还有一种是 20121001 ,这种前面四位是年 ,中间两位是月,后两位是日 。
bool IsDate(str){代码}各位牛人以及非牛人都看看

解决方案 »

  1.   

    What's your regulation?
    Mod the number by 100 to get the last two digits. See if it is between 1 and 12.
    Then divide the number by 100 to get the first several digits. It depends on your rule, any number could be a valid year number.
      

  2.   

    DateTime.prase("20121001");
    DateTime.prase("201210");
    试试呗
      

  3.   

    要排除类似这种 DateTime.prase("2012-10"), DateTime.prase("2012.10")....
      

  4.   

    bool IsDate(string s)
    {
    DateTime dt;
    return DateTime.TryParseExact(s, "yyyyMMdd", null, DateTimeStyles.None, out dt);
    }
      

  5.   

    bool IsDate(string s)
    {
    DateTime dt;
    return DateTime.TryParseExact(s, "yyyyMMdd", null, DateTimeStyles.None, out dt) || DateTime.TryParseExact(s, "yyyyMM", null, DateTimeStyles.None, out dt);
    }
    两种都支持。
      

  6.   

    B/s    protected void Button1_Click(object sender, EventArgs e)
        {
            string s = "20120230";
            if (IsDate(s))
            {
                Response.Write(s);
            }
        }    private bool IsDate(string str)
        {
            if (string.IsNullOrEmpty(str))
                return false;
            if ((str.Length != 6) && (str.Length != 8))
                return false;
            if (str.Length == 6)
            {
                str = str.Substring(0, 4) + "-" + str.Substring(4,2);
            }
            if (str.Length == 8)
            {
                str = str.Substring(0, 4) + "-" + str.Substring(4, 2) + "-" + str.Substring(6,2);
            }
            try
            {
                DateTime.Parse(str);
                return true;
            }
            catch
            {
                return false;
            }        
        }
      

  7.   

    代碼簡潔,#6樓棒!    protected void Button1_Click(object sender, EventArgs e)
        {
            string s = "2012-02";
            if (IsDate(s))
            {
                Response.Write(s);
            }
        }    private bool IsDate(string s)
        {
            DateTime dt;
            return DateTime.TryParseExact(s, "yyyyMMdd", null, System.Globalization.DateTimeStyles.None, out dt) || DateTime.TryParseExact(s, "yyyyMM", null, System.Globalization.DateTimeStyles.None, out dt);
        }
      

  8.   


    原来还有这东西,DateTime.TryParseExact和DateTime.TryParse一样吗,错误的格式也会返回一个日期。不过这个DateTime.TryParseExact似乎没出现这个问题。如果没问题以后用来验证日期时间还是挺灵活的。