我从我的页面回来了一个字符串,我想确定它是一个约会。这是我到目前为止(它的工作原理),我只是想知道这是否是“最好”的方法。我正在使用.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; }
}
使用其中之一 Parse
方法定义 DateTime
结构体。
如果字符串不可解析,这些将抛出异常,因此您可能希望使用其中一个 TryParse
相反的方法(不是很漂亮 - 它们需要一个out参数,但更安全):
DateTime myDate;
if(DateTime.TryParse(dateString,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out myDate))
{
// Use myDate here, since it parsed successfully
}
如果您知道传入日期的确切格式,可以尝试使用 ParseExact
要么 TryParseExact
采取日期和时间格式字符串(标准 要么 习惯)当试图解析日期字符串时。
我只想TryParse输入字符串:
private bool ParseDateString()
{
var theIncomingParam = Request.Params.Get("__EVENTARGUMENT").ToString();
DateTime myDate;
if (DateTime.TryParse(theIncomingParam, CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate))
{
int TheMonth = myDate.Month;
int TheDay = myDate.Day;
int TheYear = myDate.Year;
// TODO: further processing of the values just read
return true;
}
else
{
return false;
}
}
对于URL: 运用 date iso formate(YYYYMMDD
)
转换:
datetime.TryParse如上所述