Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only Date from datetime column using linq

I have a column in the database as EffectiveDate

which is the type of DateTime.

I have a linq query to get EffectiveDate from the table. but when I get I am getting EffectiveDate with time.

But in my linq query i need only Date I dont want the time for EffectiveDate.

how to write the Linq query for that?

Thanks

like image 438
user300485 Avatar asked Dec 16 '22 14:12

user300485


1 Answers

Call the Date property on any DateTime struct

EffectiveDate.Date;

or call

EffectiveDate.ToShortDateString();

or use the "d" format when calling ToString() more DateTime formats here.

EffectiveDate.ToString("d");

Writing a Linq query could look like this:

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

and if EffectiveDate is nullable you can try:

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

DateTime.Date Property

A new object with the same date as this instance, and the time value set to 12:00:00 midnight (00:00:00).

DateTime.ToShortDateString Method

A string that contains the short date string representation of the current DateTime object.

like image 85
hunter Avatar answered Dec 27 '22 11:12

hunter