不要重新发明轮子,使用DateTime.TryParseExact
专门为此目的构建的方法。在 .NET 框架中处理日期时,请忘记正则表达式和子字符串:
public static bool CheckDate(string number, out DateTime date)
{
return DateTime.TryParseExact(number, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
}
现在正如您所见,定义CheckDate
变得有点意义,因为它已经存在于 BCL 中。您只需像这样使用它:
string number = "that's your number coming from somewhere which should be a date";
DateTime date;
if (DateTime.TryParseExact(
number,
"dd/MM/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date
))
{
// the number was in the correct format
// => you could use the days, months, from the date variable which is now a DateTime
string dd = date.Day.ToString();
string mm = date.Month.ToString();
string yyyy = date.Year.ToString();
// do whatever you intended to do with those 3 variables before
}
else
{
// tell the user to enter a correct date in the format dd/MM/yyyy
}
更新:
由于我在评论部分收到一条评论说我实际上并没有回答这个问题,因此您可以使用与我推荐的方法类似的方法。但是,请向我保证,你永远不会写这样的代码,这只是为了说明 TryXXX 模式。
定义模型:
public class Patterns
{
public string DD { get; set; }
public string MM { get; set; }
public string YYYY { get; set; }
}
然后修改您的 CheckDate 方法,使其发送一个 out 参数:
public static bool CheckDate(string number, out Patterns patterns)
{
patterns = null;
string new_number = number.ToString();
if (new_number.Length == 8)
{
Patterns = new Patterns
{
YYYY = new_number.Substring(0, 4),
MM = new_number.Substring(4, 2),
DD = new_number.Substring(6, 2)
}
return true;
}
else
{
return false;
}
}
你可以这样使用:
string number = "that's your number coming from somewhere which should be a date";
Patterns patterns;
if (CheckDate(numbers, out patterns)
{
string dd = patterns.DD;
string mm = patterns.MM;
string yyyy = patterns.YYYY;
// do whatever you intended to do with those 3 variables before
}
else
{
// tell the user to enter a correct date in the format dd/MM/yyyy
}