简体   繁体   English

从可以为空的日期时间获取日期?

[英]getting date from nullable datetime ?

I have declared a field in my model as nullable datetime like this 我已经在我的模型中将一个字段声明为可以为空的日期时间

public DateTime? CallNextDate {get;set;}

in my aspx code behind I am using this linq like this: 在我的aspx代码后面我正在使用这样的linq:

q = q.AsQueryable()
    .Where(c => c.CallNextDate.Date < DateTime.Now.Date )
    .ToList();

but c.CallNextDate.Date is not available. c.CallNextDate.Date不可用。 Please suggest how to fix it 请建议如何解决它

Well, if you already know it's non-null, you can use Value to get the underlying non-nullable value: 好吧,如果你已经知道它是非null的,你可以使用Value来获取底层的非可空值:

q = q.AsQueryable()
     .Where(c => c.CallNextDate.Value.Date < DateTime.Now.Date)
     .ToList();

Or if you want to filter on that too: 或者如果你想过滤它:

q = q.AsQueryable()
     .Where(c => c.CallNextDate.Value != null &&
                 c.CallNextDate.Value.Date < DateTime.Now.Date)
     .ToList();

I'd strongly encourage you to fetch today's date once though, and reuse it for the whole query: 强烈建议你虽然一次撷取今天的日期,并重新使用其整个查询:

var today = DateTime.Today;
q = q.AsQueryable()
     .Where(c => c.CallNextDate.Value != null &&
                 c.CallNextDate.Value.Date < today)
     .ToList();

That will give you more consistency. 这会给你更多的一致性。 You should really consider whether you definitely want the system local date , by the way. 顺便说一句,你应该考虑一下你是否肯定想要系统本地日期

(Do you definitely need to use AsQueryable , by the way? That's relatively rare.) (顺便说AsQueryable ,你肯定需要使用AsQueryable吗?这种情况比较少见。)

Nullable types have a Value property which represents the underlying type: 可空类型具有Value属性,表示基础类型:

q = q.AsQueryable()
    .Where(c => c.CallNextDate.Value.Date < DateTime.Now.Date )
    .ToList();

But you will need to check to make sure the type has a value. 但是您需要检查以确保类型具有值。

q = q.AsQueryable()
    .Where(c => c.CallNextDate.HasValue && c.CallNextDate.Value.Date < DateTime.Now.Date )
    .ToList();

To get the value you can use: 要获得您可以使用的值:

 GetValueOrDefault()

Example: 例:

item.DOB is a nullable datetime. item.DOB是可以为空的日期时间。

item.DOB.GetValueOrDefault().Year

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM