Calculating age in c#.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • artist
    New Member
    • Jan 2008
    • 1

    Calculating age in c#.

    Hi,
    I want to calculate a persons age in years, months and days where combobox1 is months,combobox 2 is days and combobox3 is years. When the user clicks the button on the form,a message box pops up displaying accurate age in months,days and years.I am new to c# programming and would really appreciate if someone could suggest the code for it along with it's variables.
    Thanks.
    Artist.
  • leoiser
    New Member
    • Jul 2007
    • 41

    #2
    Here I am given a function that will calcualte age in year,month and days
    May be better option will be there.But the below option will give the result.Hope this work for you...


    private void CalcAge()
    {
    int intYR,intMonth, intDay;

    intYR = Convert.ToInt32 (txtYear.Text) ; //Get from combo
    intMonth = Convert.ToInt32 (txtMonth.Text) ;//Get from combo
    intDay = Convert.ToInt32 (txtDay.Text);//Get from combo

    DateTime dtAge = new DateTime(intYR, intMonth, intDay);
    DateTime dtToday = DateTime.Today;

    //calculating how many leap year from DOB
    //bocs I use timespan, it will include the leap yr day as 366
    int intLeapYear = 0;
    for (int i = dtAge.Year; i < dtToday.Year; i++)
    {
    if (DateTime.IsLea pYear(i))
    {
    ++intLeapYear;
    }
    }

    TimeSpan ts = dtToday.Subtrac t(dtAge);

    intDay = ts.Days -intLeapYear; //substracting leap year
    int intResult =0;

    intYR = Math.DivRem(int Day, 365,out intResult); //Year taken as 365 days
    intMonth = Math.DivRem(int Result, 30, out intResult); //Month taken as 30 days
    intDay = intResult;

    MessageBox.Show ("Hello dear! You are " + intYR.ToString( ) + " Year/s " + intMonth + " Month/s " + intDay + " Day/s");
    }

    Comment

    Working...