Get Linq Query Birth Reminder Ignoring Year

I am using C # MVC and I need to get information about a user who has a birthday in the next 20 days. using a linq to sql query that wants to compare only date and month and not year to get users having a birthday in the next 20 days, kindly help me with a linq to sql query to get users having a birthday in the next 20 days.

thanks in advance,

+4
source share
5 answers

Why not save the Birthday in a local variable, change the year to the current year, and then check to see if this happens in the next 20 days?

public bool IsBirthdayInNextTwentyDays(DateTime actualBirthday) { var birthday = actualBirthday; birthday.Year = DateTime.Now.Year; return birthday > DateTime.Now && birthday < DateTime.Now.AddDays(20); } 

Then in Linq something like:

 user.Where(u => IsBirthDayInNextTwentyDays(u.Birthday)); 

Kindness,

Dan

+3
source

This is a good decision.

  public bool IsBirthdayInNextTwentyDays(DateTime today,DateTime actualBirthday,int days) { if ((actualBirthday.DayOfYear - today.DayOfYear >= 0) ) { return (actualBirthday.DayOfYear - today.DayOfYear <= days); } else { return (actualBirthday.DayOfYear +365 - today.DayOfYear <= days); } } 

SPS Win when sharing

+1
source

Here is one way to do it. I donโ€™t really like how the computer first โ€œbirthdayโ€ this year, and then corrects it if it has already passed, but I could not think of a better way in a short time.

 from p in Persons let thisYearsBirthday = p.Birthdate.AddYears(today.Year - p.Birthdate.Year) // OR this way, although the SQL it produces it a little less simple // let thisYearsBirthday = new DateTime(today.Year, p.Birthdate.Month, p.Birthdate.Day) let nextBirthday = (thisYearsBirthday >= today) ? thisYearsBirthday : thisYearsBirthday.AddYears(1) where nextBirthday >= today && nextBirthday <= today.AddDays(20) select new { /* ... */ }; 
0
source

Use the DateTime.DayOfYear property to get an integer; January 1 == 1, last day of the year = 365/366.

Naive versions use something like

 where user.Birthday.DayOfYear - DateTime.Now.DayOfYear > 20 

This does not work when the circle of events ends - where the current day is at the end of December and the user's birthday is at the beginning of January. But start with DateTime.DayOfYear

0
source
 public static bool IsBirthdayInNextXDays(DateTime realDate, DateTime birthdayDate, int numberOfDaysToCheck) { bool isOk = false; if ((birthdayDate.DayOfYear - realDate.DayOfYear) <= numberOfDaysToCheck && (birthdayDate.DayOfYear - realDate.DayOfYear) >= 0) isOk = true; return isOk; } 
0
source

All Articles