views:

325

answers:

3

Hi all

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,

A: 

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

Daniel Elliott
Hi thanks for your reply.. the problem is am not able to convert the particular year alone to the current year, because it is read only type in which we cant able to assign the year alone "birthday.Year = DateTime.Now.Year". please help me in this regard.
kart
You can't assign a value to `DateTime.Year` like this because it is a read-only property and `DateTime` is an immutable type. What you *can* do is create a new `DateTime` with the values you want: `var birthday = new DateTime(DateTime.Now.Year, actualBirthday.Month, actualBirthday.Day;`
Lucas
Also, what will happen when `DateTime.Now` is in last 20 days of the year? Will you find birthdays coming up in January of the next year?
Lucas
A: 

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 { /* ... */ };
Lucas
A: 

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

Steve Cooper