Click here to Skip to main content
14,430,533 members
Rate this:
Please Sign up or sign in to 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 16-Feb-19 0:24am
v3
Rate this:
Please Sign up or sign in to vote.

Solution 1

   
Rate this:
Please Sign up or sign in to vote.

Solution 2

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.
   
v2

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100