1. 方法一:正則表示式
// ^ (19 | 20)\d\d[\-\/.]([1 - 9] | 1[012])[\-\/.]([1-9]|[12][0-9]|3[01])$
string pattern = @"^(19 | 20)\d\d[\-\/.]([1 - 9] | 1[012])[\-\/.]([1-9]|[12][0-9]|3[01])$";
Regex regHtml = new Regex(pattern);
Match mHtml = regHtml.Match(TextBox.Text);
if (!mHtml.Success)
sbError.AppendFormat("TextBox日期格式錯誤\\r\\n");
2. 方法二:資料轉型ParseExact
using System.Globalization;
private bool ValidateDate(string stringDateValue)
{ try
{ CultureInfo CultureInfoDateCulture = new CultureInfo("ja-JP"); //日期文化格式
DateTime d = DateTime.ParseExact(stringDateValue, "yyyy/MM/dd", CultureInfoDateCulture);
return true;
}catch
{ return false; }
}
}
3. 方法三:資料轉型 TryParseExact
DateTime Test;
if (DateTime.TryParseExact(stringDateValue, "yyyy/MM/dd", null, DateTimeStyles.None, out Test) == true)
return true;
else if(DateTime.TryParseExact(stringDateValue, "yyyy/M/d", null, DateTimeStyles.None, out Test) == true)
return true;
else
return false;
沒有留言:
張貼留言