[英]String was not recognized as a valid DateTime FormatException
[英]LINQ ToList() Method throws FormatException: String was not recognized as a valid DateTime
異常的堆棧跟蹤為:
System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi,
DateTimeStyles styles)
at lambda_method(Closure , **MyType** )
at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
MyType映射到DB中具有日期類型列的表。
現在,在我的代碼中,我有以下方法:
private static List<T> MyMethod<T>(IEnumerable<T> results)
{
if (results == null)
{
return null;
}
var filteredResults = results.AsQueryable();
return filteredResults.ToList();
}
該異常發生在以下行:return filterResults.ToList();
DB中保存的格式為:2016-12-14(YYYY-MM-DD)。 通過閱讀有關該問題的其他文章,我了解到該問題可能與服務器的區域性或時間/日期設置有關。 但是,我沒有成功重現此異常。 您對如何重現或防止此問題有任何建議?
在這些情況下,有時可以幫助您在類型中添加額外的字符串屬性,以避免數據綁定問題。 然后,您可以將數據庫值寫入該字符串字段,然后以受控方式將其轉換為另一個字段中的DateTime。
public class PocoObject
{
public string DateString { get; set; }
public DateTime Date
{
get
{
DateTime date;
return DateTime.TryParseExact(DateString,
"yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date)
? date : DateTime.MinValue;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.