簡體   English   中英

存儲在數據庫中的日期為NULL的日期返回為01/01/1900,而不是DateTime.MinValue。

[英]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.MinValue1/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 + ")";

https://docs.microsoft.com/zh-cn/dotnet/api/system.data.sqltypes.sqldatetime.minvalue?view=netframework-4.7.2

盡管最好使用DateTime作為日期類型,但是您的代碼應如下所示:

public DateTime ClosedDate
{
    get; set;
}

您還可以使用自動屬性(例如此屬性)或專用設置來滿足要求。

public DateTime ClosedDate 
{
   get;
   set
   {
     Date = DateTime.Now;
   }
}

對於字符串,可以使用DateTime.ParseDateTime.ParseExact代替Convert.ToDateTime

如果value為null,則ParseParseExact返回ArgumentNullException ;如果value包含無效的日期格式, FormatException相同的方式返回FormatException

var convertedDate = DateTime.ParseExact(dateTime, "yyyyMMdd", CultureInfo.InvariantCulture);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM