Click here to Skip to main content
15,867,835 members
Please Sign up or sign in to vote.
1.67/5 (5 votes)
See more:
hi sir

I Want to say that i am creating a registration form to work properly.
i did code for get age but it doesn't work properly .
i want year, month day but my code is only show year how will get year month & days
this is my code
C#
private void button1_Click(object sender, EventArgs e)
{
   DateTime dob = Dob_dateTimePicker.Value;
   DateTime PresentYear = Current_dateTime.Value;
            

   TimeSpan ts = PresentYear - dob;
   int Age = ts.Days / 365;

   textBox1.Text = Age.ToString() ;+//" Year" + "Month" +"Days";
           
} 


Please Explain Me How To Get Age = Year ,Month & Days

Regards
Umashankar sahu
Posted
Updated 24-Jan-21 22:55pm
v2

C#
DateTime dob = Convert.ToDateTime("18 Feb 1987");
            DateTime PresentYear = DateTime.Now;
            TimeSpan ts = PresentYear - dob;
            DateTime Age = DateTime.MinValue.AddDays(ts.Days);
            MessageBox.Show(string.Format(" {0} Years {1} Month {2} Days", Age.Year - 1, Age.Month - 1, Age.Day - 1));
 
Share this answer
 
Comments
Thomas Daniels 16-Dec-12 11:56am    
+5!
Go through this. you have the complete code for age calculation.
http://raasukutty.wordpress.com/2009/06/18/c-calculate-age-in-years-month-and-days/[^]
 
Share this answer
 
Comments
Thomas Daniels 16-Dec-12 11:56am    
+5!
Hi,
DateTime age = new DateTime(PresentYear.Subtract(dob).Ticks);
Should do the job. If you want to output a readable format,
textBox1.Text = age.Year.ToString() + " years " + age.Month.ToString() + " months " + age.Day.ToString() + " days ";
should be OK.

Regards.
 
Share this answer
 
Comments
CHill60 12-Oct-15 9:56am    
Shows incorrect age.
C#
<pre>private void datediff(TextBox d1, Label lbl, TextBox d2 = null)
        {
            int days;
            int months;
            int years;
            string date2;
            if(d2 == null)
            {
                date2 = "31/08/2019";
            }
            else
            {
                date2 = d2.Text;
            }
            try
            {
                // First Date //
                int bd = Convert.ToInt32(d1.Text.Split('/')[0]);
                int bm = Convert.ToInt32(d1.Text.Split('/')[1]);
                int by = Convert.ToInt32(d1.Text.Split('/')[2]);
                // Second Date //
                
                int cd = Convert.ToInt32(date2.Split('/')[0]);
                int cm = Convert.ToInt32(date2.Split('/')[1]);
                int cy = Convert.ToInt32(date2.Split('/')[2]);
                //**************//
                int[] mA = { 31, 28, 31, 30, 31, 30,
                      31, 31, 30, 31, 30, 31 };
                if ((cy % 4 == 0) && (cy % 100 != 0))
                {
                    mA[1] = 29;
                }
                if (cd < bd)   
                {
                    if (cm == 1)
                    {
                        cm = cm + 12;
                        cy = cy - 1;
                    }
                    cm = cm - 1;
                    cd = cd + mA[cm - 1];
                    
                }
                if (cm < bm)  
                {
                    cm = cm + 12;
                    cy = cy - 1;                    
                }
                days = cd - bd;
                months = cm - bm;
                years = cy - by;
                if (years < 0)
                {
                    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('From Date cannot be after the To Date')", true);
                    d1.Text = null;
                    if (d2 != null)
                    {
                        d2.Text = null;
                    }
                    lbl.Text = null;
                }
                else
                { 
                    lbl.Text = years + " Year " + months + " Month " + days + " Day";
                    lbl.Attributes.CssStyle.Add("color", "#3e4095");
                }
            }
            catch (Exception ex)
            {
                lbl.Text = "Please Fill value in correct format (dd/MM/yyyy)";
                lbl.Attributes.CssStyle.Add("color", "red");
                d1.Text = null;
                if (d2 != null)
                {
                    d2.Text = null;
                }
            }
        }
 
Share this answer
 
private void Agebutton_Click(object sender, EventArgs e)
{
    try
    {
        String date = DateTime.Now.Subtract(dateTimePicker1.Value).ToString();
        int days = Convert.ToInt16(date.Substring(0, date.IndexOf(".")));
        int years = (days / 365);
        int months = (days % 365) / 30;
        int weeks = ((days % 365) % 30) / 7;
        MessageBox.Show("Age=" + years + " yrs, " + months + " month's, " + weeks + " weeks", "Age calculator");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message,"Date exception");
    }
}
 
Share this answer
 
Comments
CHill60 15-Aug-19 10:35am    
I believe there are a couple of reasons why your solution is being downvoted.
1. The question was asked and answered 6.5 years ago and you haven't really added anything to existing solutions.
2. Your solution uses a Convert function which is probably why you added the unnecessary try-catch - Use TryParse functions instead.
3. If you test your code across a suitable range of dates you are going to find errors. If you want an "average" month, don't use the magic number (another reason to downvote) 30 … 30.5 will be more "accurate" and still wrong in some cases.

Reason why Solution 2 is getting lots of up-votes? It uses DateTime and Timespan. Granted it also uses a Convert function - however the value supplied is unambiguous.
I would recommend using AgeCalculator NuGet package. This library not only includes years, months, days and time components of the age but the calculation effected by the time component of the DateTime object. Optionally, it can be configured to treat Feb 29 of a leap year as Feb 28 of a non-leap year.
 
Share this answer
 
v2
Comments
OriginalGriff 24-Sep-21 1:53am    
While I applaud your urge to help people, it's a good idea to stick to new questions, rather than 9 year old ones. After that amount of time, it's unlikely that the original poster is at all interested in the problem any more!
Answering old questions can be seen as rep-point hunting, which is a form of site abuse. The more trigger happy amongst us will start the process of banning you from the site if you aren't careful. Stick to new questions and you'll be fine.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900