开发者

Get Birthday reminder Linq Query ignoring year

Am using C# MVC and i need to get the user details who having birthday with in next 20 days. using linq to sql query which wants to compare only开发者_开发问答 date and month and not the year, to fetch the users who having birthday within next 20days, anyone kindly help me with the linq to sql query to get the users who having birthday within next 20 days.

thanks in advance,


Why not store the Birthday in a local variable, change the year to the current year and then check whether it occurs 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


This is the good solution.

 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 in Sharing


Here's one way to do it. I don't really like the way it computer "this year's" birthday first and then correct it if it already passed, but I couldn't think of a better way in 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 { /* ... */ };


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

The naive versions uses something like

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

This doesn't work when the year wraps round -- where the current day is in late december and the user's birthday is in early january. But start with DateTime.DayOfYear


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜