Date comparison, ignoring the year - Linq / Entity Framework

Is there an easy way to compare dates that ignore the year using Linq and Entity Framework?

Say I have the following

var result = context.SomeEntity.Where(e => e.SomeDate > startDate);

It is assumed that SomeDate and startDate are .NET DateTime.

I would like to compare these dates without comparing the year. SomeDate can be any year. Is there an easy way to do this? The only way I could think of is to use the following:

var result = context.SomeEntity(e => 
    e.SomeDate.Month > startDate.Month ||
    (e.SomeDate.Month == startDate.Month && e.SomeDate.Day >= startDate));

This method quickly gets complicated if I also want to have endDate, since I will have to do things like take into account when the start date is at the end of the year and the end date is at the beginning.

Is there an easy way to do this?

Update:

, ... - . , , , startDate > endDate. - , , .

+3
2

var result = context.SomeEntity(e => 
    e.SomeDate.Month * 100 + e.SomeDate.Day > startDate.Month * 100 + startDate.Day
);

( , SQL-), .

+1

( ), DateTime.DayOfYear. . , , .

, , .

, , . , GetYearIgnoringOrdinal():

public static int GetYearIgnoringOrdinal(this DateTime date)
{
    return date.Month*100 + date.Day;
}

:

var result = context.SomeEntity.Where(e => e.SomeDate.GetYearIgnoringOrdinal() > startDate.GetYearIgnoringOrdinal());
0

Source: https://habr.com/ru/post/1792798/


All Articles