我一直在寻找,但没有找到解决办法。如何处理应该能够包含未初始化值(相当于null)的DateTime ?我有一个类,它可能有一个DateTime属性值设置或没有。我正在考虑将属性持有人初始化为DateTime。MinValue,然后可以很容易地检查。我想这是一个很常见的问题,你是怎么做到的?
当前回答
虽然每个人都已经给出了答案,但我将提到一种容易将datetime传递到函数中的方法
[ERROR:cannot convert system.datetime?]system.datetime)
DateTime? dt = null;
DateTime dte = Convert.ToDateTime(dt);
现在你可以在函数内部传递dte了,没有任何问题。
其他回答
如果你有时期望null,你可以使用这样的东西:
var orderResults = Repository.GetOrders(id, (DateTime?)model.DateFrom, (DateTime?)model.DateTo)
在存储库中使用可空datetime。
public Orders[] GetOrders(string id, DateTime? dateFrom, DateTime? dateTo){...}
问题本身给出了正确的答案。“如果datetime为空,你如何处理它?”,提问者在最后用datetime . minvalue给出答案。我的想法是提问者的方式应该是不变的。我建议使用DateTime。MaxValue比较,因为它不会发生直到12/31/9999。如果为真,则将field显示为日期以外的其他内容。下面是一个例子;
DateNotified = DBNull.Value.Equals(reader["DateNotified"])? Convert.ToDateTime(reader["DateNotified"]): DateTime.MaxValue
在前端 如果你使用的是网格,那么;
columns.Add(col => col.DateNotified).Css("text-right").Titled("Date Notified").RenderValueAs(c => c.DateNotified.ToString("MM/dd/yyyy").Equals(DateTime.MaxValue) ? "":c.DateNotified.ToString("MM/dd/yyyy"));
或者一个简单的观点
@Model.DateNotified.ToString("MM/dd/yyyy").Equals(DateTime.MaxValue) ? "":Model.DateNotified.ToString("MM/dd/yyyy")
如果你使用。net 2.0(或更高版本),你可以使用可空类型:
DateTime? dt = null;
or
Nullable<DateTime> dt = null;
之后:
dt = new DateTime();
你可以用:
if (dt.HasValue)
{
// Do something with dt.Value
}
或者你可以这样用:
DateTime dt2 = dt ?? DateTime.MinValue;
你可以在这里阅读更多: http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx
我会考虑使用可空类型。
DateTime吗?myDate而不是DateTime。
DateTime ?MyDateTime{拿套;}
MyDateTime = (dr["f1"] == DBNull.Value) ? (DateTime?)null : ((DateTime)dr["f1"]);
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 解析日期字符串并更改格式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?