Reputation: 579
I need to filter my nullable datetime by day month and year.
I currently trying to do it by using string comparisons. I have this in where statement in linq:
DOB.ToString().StartsWith("2/25/19") || DOB == null
But its not working. I know its because the server doesnt store the date like that, but Im unsure as to how it is storing it, and how can I retrieve it and do the comparison.
I REALLY need this to happen on the database. I cant get everything and filter in the server.
I just want linq to filter dates by day, month, and year
Any help or pointers are appreciated.
Upvotes: 0
Views: 1289
Reputation: 4089
You could try something like this (updated to include optional date components):
int? month = 2;
int? day = 25;
int? century = 19; // actual century minus one
// other LINQ here
.Where(x => x.DOB == null
|| ((month == null || x.DOB.Month = month)
&& (day == null || x.DOB.Day = day)
&& (century == null || x.DOB.Year / 100 == century)));
Upvotes: 2
Reputation: 12085
If you want to filter by day, month, year, use the example code below:
DateTime dateTime = DateTime.Now;
Console.WriteLine(dateTime.Day);
Console.WriteLine(dateTime.Month);
Console.WriteLine(dateTime.Year);
You can get those value from DateTime
object. Then, you can apply filter on it.
After reading the comment, I got your point.
For example, you enter a string like this:
string search = "2/25/2015";
Now, you want to extract the value of the string to perform filter, right? Simply do:
string[] values = search.Split('/');
Then, the values
would be [2, 25, 2015]
. First element is month, second is day, third is year, that depends on how you define the format.
Upvotes: 0
Reputation: 4113
try this:
context.Entities.Where(e => e.Date != null && e.Date.Day == 15)
you can use DateTime.Day
, DateTime.Month
, DateTime.Year
and the logical operators &&
and ||
to filter as you see fit. You must however check for nullity first or you may end up with NullExceptions
Upvotes: 0