1. 程式人生 > >C#:日期和時間的正則表示式

C#:日期和時間的正則表示式

using System.Text.RegularExpressions;

/// <summary>

///是否為日期型字串
/// </summary>
/// <param name="StrSource"> yyyy-MM-dd,嚴格按照規定</param>
/// <returns></returns>
public  static bool IsDate(string StrSource)
{
    string[] arry = Regex.Split(StrSource, "-");
    if (arry.Length != 3)
        return false;
    if (arry[0].Length != 4)
        return false;
    if (arry[1].Length != 2)
        return false;
    if (arry[2].Length != 2)
        return false;
  return Regex.IsMatch(StrSource, @"^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$");
}
/// <summary>
/// 是否為時間型字串
/// </summary>
/// <param name="source">時間字串(15:00:00)</param>
/// <returns></returns>
public static  bool IsTime(string StrSource)
{
    return Regex.IsMatch(StrSource, @"^((20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$");
}