Add the following code in your aspx page
<asp:textbox id="TextBox1" runat="server" xmlns:asp="#unknown"></asp:textbox>
<asp:textbox id="TextBox2" runat="server" xmlns:asp="#unknown"></asp:textbox>
<asp:panel runat="server" id="Panel1" xmlns:asp="#unknown">
<asp:calendar id="Calendar1" runat="server" onselectionchanged="PickDate" forecolor="Green"></asp:calendar>
</asp:panel>
Add a class to your solution:
public class AgeFormat
{
private int days = 0;
private int months = 0;
private int years = 0;
public int Days
{
get { return days; }
set { days = value; }
}
public int Months
{
get { return months; }
set { months = value; }
}
public int Years
{
get { return years; }
set { years = value; }
}
}
In code behind file(.cs) add the following:
public void PickDate(object sender, EventArgs e)
{
AgeFormat ageFormat = new AgeFormat();
int Days = Convert.ToInt32(Calendar1.SelectedDate.Day);
int Months = Convert.ToInt32(Calendar1.SelectedDate.Month);
int Years = Convert.ToInt32(Calendar1.SelectedDate.Year);
this.FindAge(Years, Months, Days, ref ageFormat);
TextBox1.Text = Calendar1.SelectedDate.Day.ToString("00") + "/" + Calendar1.SelectedDate.Month.ToString("00") + "/" + Calendar1.SelectedDate.Year.ToString("0000");
TextBox2.Text = ageFormat.Days.ToString("00") + "/" + ageFormat.Months.ToString("00") + "/" + ageFormat.Years.ToString("0000");
ToggleCalendar();
}
private void ToggleCalendar()
{
Panel1.CssClass = ("calendarHide" == Panel1.CssClass) ? ("calendarShow") : ("calendarHide");
}
private void FindAge(int years, int months, int days, ref AgeFormat ageFormat)
{
int cDay = DateTime.Now.Day;
int cMonth = DateTime.Now.Month;
int cYear = DateTime.Now.Year;
if (cDay < days)
{
if (cMonth == 1 || cMonth == 3 || cMonth == 5 || cMonth == 7 || cMonth == 8 || cMonth == 10 || cMonth == 12)
{
cDay = cDay + 31;
}
else if (cMonth == 4 || cMonth == 6 || cMonth == 9 || cMonth == 11)
{
cDay = cDay + 30;
}
else if (cMonth == 2)
{
if (cYear % 4 == 0)
{
cDay = cDay + 29;
}
else
{
cDay = cDay + 28;
}
}
cMonth--;
}
if (months > cMonth)
{
cMonth = cMonth + 12;
cYear--;
}
ageFormat.Days = cDay - days;
ageFormat.Months = cMonth - months;
ageFormat.Years = cYear - years;
}
The above methods will calculate the days, months and Years.
But if you only require the years of the age then don't hook up on method FindAge and change its definition (as ScArcher2 wrote in above mentioned
link) following:
private int FintAge(int years, int months, int days)
{
int ageYears = 0;
double dob = ((years * 100) + months * 100) + days;
double cDate = ((DateTime.Now.Year * 100) + DateTime.Now.Month * 100) + DateTime.Now.Day;
ageYears = Convert.ToInt32((cDate - dob) / 10000);
return ageYears;
}
Wish you best of luck.