tags:

views:

655

answers:

2

Hello,

I have a DateTime object with a person's birthday. I created this object using the person's year, month and day of birth, in the following way:

DateTime date = new DateTime(year, month, day);

I would like to know how many days are remaining before this person's next birthday. What is the best way to do so in C# (I'm new to the language)?

Thanks

+10  A: 

// birthday is a DateTime containing the birthday

DateTime today = DateTime.Today;
DateTime next = new DateTime(today.Year,birthday.Month,birthday.Day);

if (next < today)
    next = next.AddYears(1);

int numDays = (next - today).Days;
Philippe Leybaert
TotalDays returns a double : http://msdn.microsoft.com/en-us/library/system.timespan.totaldays.aspx
Mac
+1 This is close to the "manual" way I'm using right now, I thought maybe there's a neat C# trick to simplify it.
Roee Adler
@Mac: fixed. Thanks
Philippe Leybaert
+1, i thought he used DateTime.Now which includes the current time.
Leon Tayson
+1  A: 

Try this method

private int GetDaysBeforeBirthday(DateTime birthdate)
{
    DateTime nextBday = new DateTime(DateTime.Now.Year, birthdate.Month, birthdate.Day);
    if (DateTime.Today > nextBday)
        nextBday = nextBday.AddYears(1);
    return (nextBday - DateTime.Today).Days;
}

just pass your birthdate and it will return the remaining days before your next birthday

Leon Tayson
How is this different from Philippe's answer?
Roee Adler