与.NET约会的最佳方式?

fre*_*hie 11 c# asp.net parsing date

我从我的页面回来了一个字符串,我想确定它是一个约会.这是我到目前为止(它的工作原理),我只是想知道这是否是"最好"的方法.我正在使用.NET 4.

int TheMonth =0;
int TheDay = 0;
int TheYear = 0;
DateTime NewDate;

var TheIncomingParam = Request.Params.Get("__EVENTARGUMENT").ToString();

char[] TheBreak = { '/' };
string[] TheOutput = TheIncomingParam.Split(TheBreak);

try { TheMonth = Convert.ToInt32(TheOutput[0]); }
catch { }

try { TheDay = Convert.ToInt32(TheOutput[1]); }
catch { }

try { TheYear = Convert.ToInt32(TheOutput[2]); }
catch { }

if (TheMonth!=0 && TheDay!=0 && TheYear!=0)
{
        try { NewDate = new DateTime(TheYear, TheMonth, TheDay); }
        catch { var NoDate = true; }
}
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 13

使用结构中Parse定义的方法之一DateTime.

如果字符串不可解析,这些将抛出异常,因此您可能希望使用其中一种TryParse方法(不是很漂亮 - 它们需要out参数,但更安全):

DateTime myDate;
if(DateTime.TryParse(dateString, 
                  CultureInfo.InvariantCulture, 
                  DateTimeStyles.None, 
                  out myDate))
{
   // Use myDate here, since it parsed successfully
}
Run Code Online (Sandbox Code Playgroud)

如果您知道传入日期的确切格式,则可以尝试在尝试解析日期字符串时使用ParseExactTryParseExact采用日期和时间格式字符串(标准自定义).