-2

i have a code by which i can find the only number of days for count next birthday but i want not only days but also month.

        DateTime birthday=dtp.Value;
        DateTime td = DateTime.Today;
        DateTime next = new DateTime(td.Year, birthday.Month, birthday.Day);

        if (next < td)
        {
            next = next.AddYears(1);
        }

        int d = (next - td).Days;`

if my birthdate is 29 Oct 1994 than in int d i will get the 44 days( number of days remaining) but i want 1 month and 14 days as an output

Please help me for this solution.

Android Dev
  • 1,496
  • 1
  • 13
  • 25

2 Answers2

1

Try this:

int months = 0;
for (; months< 12; )
{
    td = td.AddMonths(1);
    if (td > next)
    {
        td = td.AddMonths(-1);
        break;
    }
    months++;
}

Insert that just before your "int d..." line. It should give you the number of months, and your day calculation should be < one month.

Lorek
  • 855
  • 5
  • 11
0

Problem is, that "a month" is not "a month" but a count of days between 28 and 31.

However, by applying AddMonths you can get fairly close to a uniform and useful method:

DateTime birthday = new DateTime(1980, 11, 19);
DateTime today = DateTime.Today;
int months = 0;
int days = 0;

DateTime nextBirthday = birthday.AddYears(today.Year - birthday.Year);
if (nextBirthday < today)
{
    nextBirthday = nextBirthday.AddYears(1);
}

while (today.AddMonths(months + 1) <= nextBirthday)
{
    months++;
}
days = nextBirthday.Subtract(today.AddMonths(months)).Days;

Console.WriteLine("Next birthday is in {0} month(s) and {1} day(s).", months, days);

Result:

Next birthday is in 2 month(s) and 4 day(s).
Gustav
  • 53,498
  • 7
  • 29
  • 55
  • Please note, that you have to use `AddYears` as shown to get a precise calculation for the next birthday. – Gustav Sep 15 '15 at 08:17