0

I am trying to get the difference between two datetimepickers.

For example: Between X date and Y date, have been past X days, Y months and Z years.

So, if I'd put in the first datetimepicker my birth date and in the second the day of today, I would my exact age, for example: "20 days, 3 months and 26 years".

I tried a few codes, but the results are not correct.

Thanks in advance.

The code is:

string age = "Tu age es de:\n";
age = age + ((Math.Abs(DateTime.Today.Day - dtpage.Value.Day)).ToString()) + " days, ";
age = age + ((Math.Abs(DateTime.Today.Month - dtpage.Value.Month)).ToString()) + " months";
age = age + " y " + ((Math.Abs(DateTime.Today.Year - dtpage.Value.Year)).ToString()) + " years";
MessageBox.Show(age);

EDIT: Solved in C# calculate accurate age

Community
  • 1
  • 1
user3108594
  • 225
  • 2
  • 5
  • 13

4 Answers4

0

Please show the code if this answer is not sufficient, but if you're talking about DateTime objects, just use the Subtract method.

BlueMonkMN
  • 25,079
  • 9
  • 80
  • 146
0

Try This:

DateTime birthdayDate = DateTime.Now; //get the date from datetimepicker
var dateTimeResult = DateTime.Now.Subtract(birthdayDate);
Only a Curious Mind
  • 2,807
  • 23
  • 39
0

I think Datediff will accomplish this.

Edit - here:

string diff = DateAndTime.DateDiff(DateInterval.Second, DateTimePicker1.Value, DateTimePicker2.Value);
Interaction.MsgBox(diff);

Now just format the seconds.

dave88
  • 312
  • 5
  • 14
0

I think you might have to write a couple of your own lines of code, which is not too hard if you look at your classes. Here is a simple example, you may need to check for a negative month value and if so add 12 to it, since you would be carrying a year over.

        DateTime d = DateTime.Now;
        DateTime d2 = DateTime.Now.AddMinutes(-28938923);

        int years = d.Year - d2.Year;
        int months = d.Month - d2.Month;
        int days = d.Day - d2.Day;

        if (days < 0)
        { 
            // borrow a month
            months--;
            // use your brain power to pick the correct month.  I have not thought this step out.
            days += DateTime.DaysInMonth(d.Month);  
        }
        if (months < 0)
        { 
            // borrow a year
            years--;
            months += 12;
        }
Adam Heeg
  • 1,704
  • 1
  • 14
  • 34