Click here to Skip to main content
15,887,349 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am writing some code to calculate two dates in four parts as years, months, weeks, and days viz; if someone's DOB is 15-12-1988 I want to show this like 30 years,2 months, 1 day. It does not response properly. Please provide me some other codes to solve it

What I have tried:

double months;
     double years;
     //double weeks;
     double days;
     DateTime inTime = Convert.ToDateTime(dateTimePicker1.Text);
     DateTime outTime = Convert.ToDateTime(dateTimePicker2.Text);
     if (outTime >= inTime)
     {
         textBox3.Text = outTime.Subtract(inTime).Days.ToString() + " days ";

         years = (outTime - inTime).Days / 365;
         months = (outTime - inTime).Days / 12;
         days = (outTime - inTime).Days / 30;
         textBox2.Text = Convert.ToInt32(years).ToString() + " Years," + Convert.ToInt32(months).ToString() + " Months," + Convert.ToInt32(days).ToString() + " Days" ;


     }
Posted
Updated 15-Feb-19 23:24pm
v3

 
Share this answer
 
Why are you using the text field from the datetimepickers which you then need to convert to DateTime values? Use the Value property in the first place. You also do not need all those calulations since the TimeSpan Struct (System) | Microsoft Docs[^] can provide them automatically. See OriginalGriff's answer above.
 
Share this answer
 
v2

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