[英]Html.TextBoxFor value for datetime.minvalue always turns into 01/01/2001 or disappears
[英]Date stored in DataBase as NULL is returned as 01/01/1900 and not as DateTime.MinValue
我有一個邏輯,可以執行以下操作:
string myData = Convert.ToDateTime(Info.ClosedDate) == DateTime.MinValue ? String.Empty : "(" + Info.ClosedDate + ")";
如果未在數據庫中將其存儲為NULL,則應在括號中返回ClosedDate。 否則,它將返回一個空字符串。
的值Convert.ToDateTime(Info.ClosedDate)
是01/01/1900
和的值DateTime.MinValue
是1/1/0001 12:00:00 AM
因此,條件永遠不會返回String.Empty
當前對象中的字段表示為:
public string ClosedDate
{
get { return _ClosedDate; }
set { _ClosedDate = value; }
}
最好的解決方案是什么?
不要將DateTime
類型存儲或建模為string
。
這適用於數據存儲,也適用於代碼中的模型。 如果它在數據庫中可以為空,則可以在代碼中將其建模為Nullable<DateTime>
(備用表示法DateTime?
)。 僅在可能的最后一刻(通常在表示層中)將其轉換為string
。 如果這樣做,則在讀/寫數據存儲區時無需進行任何類型轉換。 您還可以避免在值解釋上產生歧義( 例如,什么值是null或將其本地化為“ dd / MM / yyyy”或“ MM / dd / yyyy” )。
private DateTime? _ClosedDate;
public DateTime? ClosedDate
{
get { return _ClosedDate; }
set { _ClosedDate = value; }
}
旁注:以上內容也可以建模為auto屬性,但我沒有這樣做,因為尚不清楚該字段如何在模型中使用
如果您不確定如何將DateTime
實例作為本機格式的參數傳遞給ADO.NET查詢,請查看此先前的問題/答案: 如何將用戶提供的輸入添加到SQL語句?
您可以與SqlDateTime.MinValue
進行比較
Convert.ToDateTime(Info.ClosedDate) == SqlDateTime.MinValue? String.Empty : "(" + Info.ClosedDate + ")";
盡管最好使用DateTime作為日期類型,但是您的代碼應如下所示:
public DateTime ClosedDate
{
get; set;
}
您還可以使用自動屬性(例如此屬性)或專用設置來滿足要求。
public DateTime ClosedDate
{
get;
set
{
Date = DateTime.Now;
}
}
對於字符串,可以使用DateTime.Parse
或DateTime.ParseExact
代替Convert.ToDateTime
。
如果value為null,則Parse
或ParseExact
返回ArgumentNullException
;如果value包含無效的日期格式, FormatException
相同的方式返回FormatException
。
var convertedDate = DateTime.ParseExact(dateTime, "yyyyMMdd", CultureInfo.InvariantCulture);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.