日期:2014-05-17  浏览次数:20766 次

c# 验证年月时间格式
如:201210 如何验证这样的年月组合,前面四位是年 ,后台两位是月。

 还有一种是 20121001 ,这种前面四位是年 ,中间两位是月,后两位是日 。


bool IsDate(str){

代码

}

各位牛人以及非牛人都看看

------解决方案--------------------
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.
------解决方案--------------------
DateTime.prase("20121001");
DateTime.prase("201210");
试试呗
------解决方案--------------------
探讨
DateTime.prase("20121001");
DateTime.prase("201210");
试试呗

------解决方案--------------------
C# code
    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
C# code

    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樓棒!
C# code

    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);
    }