2011-04-21 145 views
4

我在數據庫中有一列爲EffectiveDate如何從日期時間列使用LINQ的日期

這是DateTime的類型。

我有一個linq查詢來從表中得到EffectiveDate。但是當我得到時,我隨着時間的推移獲得了EffectiveDate。

但在我的linq查詢中,我只需要日期我不想爲EffectiveDate的時間。

如何編寫Linq查詢呢?

感謝

+1

你使用的是實體框架嗎? – 2011-04-21 17:44:56

回答

11

調用Date財產上的任何DateTime結構

EffectiveDate.Date; 

或致電

EffectiveDate.ToShortDateString(); 

或致電ToString()多個DateTime格式here時,使用 「d」 格式。

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對象的短日期字符串表示的字符串。

+1

我無法調用DateTime.Date。其投擲運行時間錯誤。 – user300485 2011-04-21 17:41:25

+0

@user究竟哪個錯誤? – 2011-04-21 17:41:58

+2

@user如果您使用的是Entity框架,那麼您就對EDM.DateTime沒有.Date屬性。查看[EDM.DateTime](http://msdn.microsoft.com/en-us/library/bb387157.aspx)瞭解您可以使用哪些方法。 – Chad 2011-04-21 18:31:32