Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate days remaining to a birthday?

Tags:

c#

datetime

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)?

like image 918
Roee Adler Avatar asked Jul 23 '09 07:07

Roee Adler


People also ask

How does the birthday age calculator work?

The birthday age calculator calculates the remaining days for your next coming birthday when you select your date of birth. The birthday age calculator also tells you about your heartbeat, sleeping time, and the number of times you have laughed from the day you have taken birth.

How do I work out how many days until my birthday?

Use our birthday calculator to work out the number of days until your next birthday. We calculate this based upon your birth date and today's date. On what day was I born? Use the birthday calculator to find out how many hours, days, months and years you've been alive for and what day you were born on.

How do I calculate the days remaining from today?

If you need to calculate days remaining from today, use the TODAY function like so: The TODAY function will always return the current date. Note that after the end_date has passed, you'll start to see negative results, because the value returned by TODAY will be greater than the end date.

How to count days until next birthday in Excel?

Count days until next birthday with formulas. 1 Step 2. Get today’s date. Now we need to get Today’s date with formula. Select cell B2, enter the below formula into it, and press Enter ley. Then you ... 2 Step 3. Get the date of next birthday. 3 Step 4. Get the remaining days until next birthday.


1 Answers

// 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;

This trivial algorithm fails if the birthday is Feb 29th. This is the alternative (which is essentially the same as the answer by Seb Nilsson:

DateTime today = DateTime.Today;
DateTime next = birthday.AddYears(today.Year - birthday.Year);

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

int numDays = (next - today).Days;
like image 78
Philippe Leybaert Avatar answered Nov 09 '22 02:11

Philippe Leybaert