日期:2014-05-17 浏览次数:20957 次
    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);
    }
------解决方案--------------------
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;
        }        
    }
------解决方案--------------------
代碼簡潔,#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);
    }