你的代碼表明,該變量可以是日期或看起來像一個日期的字符串。日期你可以簡單地返回一個強制轉換,但字符串必須解析。解析帶來兩個警告;
,如果你不能確定這個字符串可以解析,然後使用DateTime.TryParse()
。
始終包含對您要解析的文化的引用。 ToShortDateString()
在不同的地方返回不同的輸出。你幾乎肯定會用同樣的文化來解析。我建議這個功能處理這兩種情況;
private DateTime ParseDateTime(object data)
{
if (data is DateTime)
{
// already a date-time.
return (DateTime)data;
}
else if (data is string)
{
// it's a local-format string.
string dateString = (string)data;
DateTime parseResult;
if (DateTime.TryParse(dateString, CultureInfo.CurrentCulture,
DateTimeStyles.AssumeLocal, out parseResult))
{
return parseResult;
}
else
{
throw new ArgumentOutOfRangeException("data",
"could not parse this datetime:" + data);
}
}
else
{
// it's neither a DateTime or a string; that's a problem.
throw new ArgumentOutOfRangeException("data",
"could not understand data of this type");
}
}
然後調用這樣;
ParseDateTime(g[0]["MyUntypedDateField").ToShortDateString();
請注意,壞的數據會引發異常,所以您需要捕獲該異常。
另外; 'as'操作符不適用於DateTime數據類型,因爲它僅適用於引用類型,而DateTime是值類型。
當對象不是DateTime時,請不要使用Parse,而要使用ParseExact並指定預期的日期和時間格式,以避免依賴於當前的用戶區域設置。看到我對這個問題的回答。 – qbeuek 2008-09-15 06:22:19