1

I am designing a practice visual c# program that has you pick your birth date from a dateTimePicker and comparing it to the current date to display in a textBox what your current age is.

I would like to factor in which day of the month you picked to refine the age result rather than just assuming you're a certain age because you were born in that particular month.

This is what I have so far:

public void button1_Click(object sender, EventArgs e)
        {

            var birthdayYear = dateTimePicker1.Value.Year;
            var birthdayMonth = dateTimePicker1.Value.Month;
            var birthdayDay = dateTimePicker1.Value.Day;
            var currentYear = DateTime.Now.Year;
            var currentMonth = DateTime.Now.Month;
            var currentDay = DateTime.Now.Day;

            int currentAge = DateTime.Now.Year - dateTimePicker1.Value.Year;

            if (birthdayMonth >= currentMonth)
            {

                currentAge--;

            }


            string currentResult = Convert.ToString(currentAge);

            ageResult.Text = currentResult;
}

1 Answers1

-1

Do not try to implement date math yourself. Date math is notoriously difficult to get right and has a fair share of tricky edge cases.

Krumelur
  • 31,081
  • 7
  • 77
  • 119
  • 1
    `TimeSpan` does not include Years as they are not a uniform amount of time. The way to calculate age is to get the difference in the years and then check if the current date is before the birth day for this year and subtract 1 if it is. – juharr Jun 10 '20 at 19:24
  • Correct, I mixed up the TimeSpan with the DateTimeOffset class. The latter stores the point of origin and does indeed have the year, month, etc. – Krumelur Jun 11 '20 at 20:54
  • You don't seem to understand what `DateTimeOffset` is either. It's a `DateTime` and an offset from UTC, not some offset from another `DateTime`. If you try to create one with an offset less than -14 hours or more than 14 hours it will fail. – juharr Jun 12 '20 at 00:24
  • Interesting. Actually never tried that as my use cases have been within a day. I don’t see anything in the docs indicating this limit, but I removed that part as I am unable to verify now. – Krumelur Jun 12 '20 at 21:41