我用下面的程序判断,我提示用户输入格式为2008-8-8可是用户输入2008-8,下面的也判断是正确,大家有没有好办法
try
{
Convert.ToDateTime(txt1.Text.Trim());//或者DateTime.Parse(txt1.Text.Trim());
}
catch
{
}
try
{
Convert.ToDateTime(txt1.Text.Trim());//或者DateTime.Parse(txt1.Text.Trim());
}
catch
{
}
bool b=DateTime.TryParseExact("2008-01", "yyyy-MM", null, System.Globalization.DateTimeStyles.None, out tt);
bool b=DateTime.TryParseExact("2008-01", "yyyy-MM", null, System.Globalization.DateTimeStyles.None, out tt);
dateString = "5/01/2009 09:00";
if (DateTime.TryParseExact(dateString, "M/dd/yyyy hh:mm", enUS,
DateTimeStyles.None, out dateValue))
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
dateValue.Kind);
else
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
try
{
Convert.ToDateTime(“2008-8”);
}
catch
{
}
不到catch 里面
if (!System.Text.RegularExpressions.Regex.IsMatch("2008-08-8", @"^[\d]{4}-[\d]{2}-[\d]{2}$"))
throw new ArgumentException();
if (!System.Text.RegularExpressions.Regex.IsMatch("2008-8", @"^[\d]{4}-[\d]{1,2}-[\d]{1,2}$"))
throw new ArgumentException();
这样不行9999-99-99的形式也是正确的
using System.Globalization;namespace Parse
{
class Class1
{
public static void Main(string[] args)
{
// Assume the current culture is en-US.
// The date is February 16, 1992, 12 hours, 15 minutes and 12 seconds. string myDateTimeValue = "2/16/1992 12:15:12";
DateTime myDateTime = DateTime.Parse(myDateTimeValue);
Console.WriteLine("1) myDateTime = {0}", myDateTime);// Reverse month and day to conform to a different culture.
// The date is February 16, 1992, 12 hours, 15 minutes and 12 seconds. IFormatProvider culture = new CultureInfo("fr-FR", true);
string myDateTimeFrenchValue = " 16/02/1992 12:15:12";
DateTime myDateTimeFrench =
DateTime.Parse(myDateTimeFrenchValue,
culture,
DateTimeStyles.NoCurrentDateDefault);
Console.WriteLine("2) myDateTimeFrench = {0}", myDateTimeFrench);
// The date is February 16, 1992, 12 hours, 15 minutes and 12 seconds. string[] expectedFormats = {"G", "g", "f" ,"F"};
myDateTimeFrench =
DateTime.ParseExact(myDateTimeFrenchValue,
expectedFormats,
culture,
DateTimeStyles.AllowWhiteSpaces);
Console.WriteLine("3) myDateTimeFrench = {0}", myDateTimeFrench);
}
}
}
/*
This example yields the following results:1) myDateTime = 2/16/1992 12:15:12 PM
2) myDateTimeFrench = 2/16/1992 12:15:12 PM
3) myDateTimeFrench = 2/16/1992 12:15:12 PM
*/
{
throw new ArgumentException();}
其中str是日期字符串
throw new ArgumentException();
赞成
richTextBox2.Text += "符合" + "\n";
else
richTextBox2.Text += "不符合" + "\n";