[英]C# Validating date pattern
我正在一个框架中生成代码。 日期和时间字段的属性之一是其格式。 它必须是DateTime.ToString()
接受的格式,例如dd/MM/yyyy
。 如何验证应用程序中键入的掩码是否为.ToString()
的有效日期时间模式?
第一个变体使用System.Globalization。 二是脏。
static bool ValidateFormat(string customFormat)
{
return !String.IsNullOrWhiteSpace(customFormat) && customFormat.Length > 1 && DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns().Contains(customFormat);
}
static bool ValidateFormat(string customFormat)
{
try
{
DateTime.Now.ToString(customFormat);
return true;
}
catch
{
return false;
}
}
就个人而言,如果实际要求是给定格式必须导致DateTime.Now.ToString(format)
不引发异常,那么在我看来,最可靠的方法是在try / catch块中使用该代码,如果它会适当地引发异常处理。
要注意的一件事是ToString
代码依赖于DateTimeFormatInfo
对象。 尽管我不确定,这可能会使某些格式无效。 如果这样做的话,很可能会使用不同的日历等。 但是,仅本地化选项可能需要它。 当然,值得对所有您感兴趣的语言环境(或至少具有代表性的示例)进行测试,或者最好仅使用DateTime.ToString
的ToString(string format, IFormatProvider provider)
重载。
正如其他人对问题编程的评论,而期望异常通常不是很好的做法,但在这种情况下,我认为这是最佳匹配,因为a)完全符合要求,b)其他选项很难编程,因此更有可能出现错误。
这是您可能使用的示例方法。 请注意,我专门捕获了FormatException而不是所有异常,以防万一其他异常情况出了我们不想捕获的错误。
public static bool ValidateDateFormat(string format, IFormatProvider provider)
{
try
{
DateTime.Now.ToString(format, provider);
return true;
}
catch(FormatException)
{
return false;
}
}
很简单...
class Program
{
static void Main(string[] args)
{
string s = "yyyy-MM-dd";
string reg = @"^\bdd/MM/yyyy\b$";
string reg1 = @"^\byyyy-MM-dd\b$";
if (Regex.IsMatch(s, reg))
Console.WriteLine("true");
else if (Regex.IsMatch(s, reg1))
Console.WriteLine("true");
// and so on..
Console.ReadLine();
}
}
要么
static void Main(string[] args)
{
string s = "dd/MM/yyyy";
string reg = @"(?<dateMatch>(^\bdd/MM/yyyy\b$)|(^\byyyy-MM-dd\b$))";
if (Regex.IsMatch(s, reg))
Console.WriteLine("true");
Console.ReadLine();
}
此方法将匹配两个日期模式。 “ dd / MM / yyyy”和“ yyyy-MM-dd”。 根据需要添加任意数量的模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.