//Example 2 - Validate Date for the format MM/DD/YYYY
private bool ValidateDate(string stringDateValue)
{
try
{
CultureInfo CultureInfoDateCulture = new CultureInfo("en-US");
DateTime d = DateTime.ParseExact(stringDateValue, "MM/dd/yyyy", CultureInfoDateCulture);
return true;
}
catch
{
return false;
}
}
如何在不使用try和catch的情况下设置此代码?
答案 0 :(得分:9)
private bool ValidateDate(string stringDateValue)
{
DateTime dummy;
CultureInfo CultureInfoDateCulture = new CultureInfo("en-US");
return DateTime.TryParseExact(stringDateValue, "MM/dd/yyyy",
CultureInfoDateCulture, DateTimeStyles.None,
out dummy);
}
答案 1 :(得分:1)
改为使用DateTime.TryParseExact
,这样您就可以使用条件if
来控制流量。
答案 2 :(得分:0)
您可以尝试:
CultureInfo CultureInfoDateCulture = new CultureInfo("en-US");
DateTime date;
bool works = DateTime.TryParseExact(dateString, "MM/dd/yyyy", CultureInfoDateCulture ,
DateTimeStyles.None, out date))
答案 3 :(得分:0)
我认为最简单的方法是:
private static bool ValidateDate(string stringDateValue)
{
DateTime dummy;
return DateTime.TryParseExact(stringDateValue, "MM/dd/yyyy", CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.None, out dummy);
}