繁体   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