-4
//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 的情况下设置此代码工作?

4

4 回答 4

9

使用DateTime.TryParseExact

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);
}
于 2013-08-05T12:00:43.410 回答
1

改为使用DateTime.TryParseExact,这将让您使用有条件的if.

于 2013-08-05T12:00:41.593 回答
0

我认为最简单的方法是:

    private static bool ValidateDate(string stringDateValue)
    {
        DateTime dummy;
        return DateTime.TryParseExact(stringDateValue, "MM/dd/yyyy", CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.None,  out dummy);
    }
于 2013-08-05T12:07:44.707 回答
0

你可以试试:

CultureInfo CultureInfoDateCulture = new CultureInfo("en-US");
DateTime date;

bool works = DateTime.TryParseExact(dateString, "MM/dd/yyyy", CultureInfoDateCulture , 
                       DateTimeStyles.None, out date))
于 2013-08-05T12:02:27.850 回答