简体   繁体   中英

age should be calculated based on date of birth in asp.net?

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:

在此处输入图像描述

which place I need to change my logic?

Try this one:

var age = DateTime.Now - birthdate;

Instead of:

int age = DateTime.Now.Year - birthdate.Year;
    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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM