【问题标题】:How to get only Date from datetime column using linq如何使用 linq 从日期时间列中仅获取日期
【发布时间】:2011-04-21 17:39:04
【问题描述】:

我在数据库中有一个列作为 EffectiveDate

这是 DateTime 的类型。

我有一个 linq 查询来从表中获取 EffectiveDate。但是当我得到时,我会随着时间的推移得到 EffectiveDate。

但在我的 linq 查询中,我只需要 Date 我不想要 EffectiveDate 的时间。

如何为此编写 Linq 查询?

谢谢

【问题讨论】:

  • 你在使用实体框架吗?

标签: asp.net linq linq-to-sql asp.net-mvc-2


【解决方案1】:

在任何DateTime 结构上调用Date 属性

EffectiveDate.Date;

或致电

EffectiveDate.ToShortDateString();

或调用ToString()时使用“d”格式更多日期时间格式here

EffectiveDate.ToString("d");

编写 Linq 查询可能如下所示:

someCollection.Select(i => i.EffectiveDate.ToShortDateString());

如果EffectiveDate 可以为空,您可以尝试:

someCollection
    .Where(i => i.EffectiveDate.HasValue)
    .Select(i => i.EffectiveDate.Value.ToShortDateString());

DateTime.Date Property

与此实例具有相同日期的新对象,时间值设置为午夜 12:00:00 (00:00:00)。

DateTime.ToShortDateString Method

包含当前 DateTime 对象的短日期字符串表示形式的字符串。

【讨论】:

  • 我无法调用 DateTime.Date。它抛出运行时错误。
  • @user 如果您使用的是实体框架,那么您是对的,EDM.DateTime 没有 .Date 属性。查看EDM.DateTime 了解您可以使用哪些方法。
  • @Chad 它被标记为 linq-to-sql 但如果这不是 OP 使用的,那么你是正确的
猜你喜欢
  • 2013-11-29
  • 2016-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 1970-01-01
  • 2019-04-04
  • 1970-01-01
相关资源
最近更新 更多