0

I m new in asp.net

I want when user select date of birth then automatically calculate their age and fill up the age text box and I performing one logic but somewhere My logic is wrong?

code:

default.aspx

<form>
            <label for="date"><b>Date Of Birth:</b></label>
            <asp:Calendar  ID="txtdate" placeholder="Select Your Date Of Birth" runat="server" OnSelectionChanged="txtdate_SelectionChanged"></asp:Calendar>


            <label for="age"><b>Age:</b></label>
            <asp:TextBox ID="txtage" runat="server" placeholder="Age"></asp:TextBox>
</form>

default.aspx.cs

        protected void txtdate_SelectionChanged(object sender, EventArgs e)
        {
            DateTime birthdate=txtdate.SelectedDate.Date;  //select date from calender

            int age = DateTime.Now.Year - birthdate.Year;

            txtage.Text = age.ToString();
        }

        protected void age_TextChanged(object sender, EventArgs e)
        {

        }

when I select the date of birth from calender(1/12/2017) In the watch window then display the 3 year but I want to display 2 years 4 months 24 days

watch window:

enter image description here

which place I need to change my logic?

2 Answers2

1

Try this one:

var age = DateTime.Now - birthdate;

Instead of:

int age = DateTime.Now.Year - birthdate.Year;
Yojizan
  • 136
  • 3
  • when I select 28/12/2018 then display the age this type 575.15:20:13.7173816 – rahul_patil Apr 25 '20 at 09:53
  • here I m missing something ```txtage.Text = age.ToString();``` I m writing the tostring that is the reason the date is not properly shown? what can I do here – rahul_patil Apr 25 '20 at 09:56
1
    DateTime Birth = txtdate.SelectedDate.Date;
    DateTime Today = DateTime.Now;


    TimeSpan Span = Today - Birth;


    DateTime Age = DateTime.MinValue + Span;


    // note: MinValue is 1/1/1 so we have to subtract...
    int Years = Age.Year - 1;
    int Months = Age.Month - 1;
    int Days = Age.Day - 1;
    txtage.Text = Years.ToString() + " Years, " + Months.ToString() + " Months, " + Days.ToString() + " Days";
  • can u change this line ```DateTime Birth = txtdate.SelectedDate.Date;``` accordingly your code is working fine – rahul_patil Apr 25 '20 at 10:23
  • and one thing I notice many online age calculators is displaying the wrong date that is the reason testing for multi-time – rahul_patil Apr 25 '20 at 10:31