我正在解析ASP.NET WebForms
頁面中的日期時間值,並且日期字符串一直被DateTime.TryParseExact()
方法拒絕,即使它明確地匹配提供的格式字符串之一。DateTime.TryParseExact()拒絕有效格式
這似乎是我的機器上不能在家裏,但在生產服務器上的工作,所以我參與思維的本地日期設置,但即使我提供一個IFormatProvider (CultureInfo)
對象作爲參數
出現此錯誤下面的代碼:
DateTime startDate;
string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy",
"dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy"};
var errStart = row.FindControl("errStartDate"); //my date format error message
if (!DateTime.TryParseExact(txtStartDate.Text, formats, null, DateTimeStyles.None, out startDate))
{
errStart.Visible = true; //we get here even with a string like "20/08/2012"
return false;
}
else
{
errStart.Visible = false;
}
注意我給上面一個null FormatProvider
,但出現同樣的問題,當我提供CultureInfo
對象 (CultureInfo provider = new CultureInfo("en-US"))
此參數。
我錯過了什麼?
在美國文化中,日期格式爲M/d/Y不是D/M/Y – StuartLC 2012-08-17 04:50:27
即使不提FormatProvider,該代碼似乎工作正常爲了我。嘗試指定InvariantCulture。 – danish 2012-08-17 04:51:00