I've been given two dates that takes their values from two respective dtpickers.
I've got to calculate the exact amount of days, months and years between them.
So I tried this:
Dim dteStartDate As Date
Dim dteEndDate As Date
dteStartDate = dtpStart.Text
dteEndDate = dtpEnd.Text
dteResultDays = DateDiff(DateInterval.Day, dteStartDate, dteEndDate)
dteResultMonths = DateDiff(DateInterval.Month, dteStartDate, dteEndDate)
dteResultYears = DateDiff(DateInterval.Year, dteStartDate, dteEndDate)

The problem is that this method gives me ALL of the amount of respective days, months and years passed, but I need to split them in the correct way. Ex, between 28/2/98 and 13/1/2007 the result should be 15 days, 10 months and 8 years. And above all, another bug is that the function indicates one month more (or one year more) with only one day (or month) passed between the two dates! They told me I shoul use TimeSpan,but i don't Know how...

Any brighter ideas? I'd be very grateful...and it will grant you an excellent karma :-)

This might not be the best solution, but if you don't find anything better:

years.Text = DateDiff(DateInterval.Year, Start.Value, _End.Value)
 months.Text = DateDiff(DateInterval.Month, _
            DateAdd(DateInterval.Year, CInt(years.Text), Start.Value), _End.Value)
 days.Text = DateDiff(DateInterval.Day, _
            DateAdd(DateInterval.Month, CInt(months.Text), _
            DateAdd(DateInterval.Year, CInt(years.Text), Start.Value)), _End.Value)
 hours.Text = DateDiff(DateInterval.Hour, _
    DateAdd(DateInterval.Day, CInt(days.Text), _
    DateAdd(DateInterval.Month, CInt(months.Text), _
    DateAdd(DateInterval.Year, CInt(years.Text), Start.Value) _
    )), _End.Value)

Sometimes Excel logic can do wonders.

Comments
Good attention to the request!

adam_k nailed it.
I wasn't paying attention.
Here is my WinForms version:

Public Class Form1
   Private Sub bnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bnCalculate.Click
      Dim dateStart As Date = DateTimePickerStart.Value
      Dim dateEnd As Date = DateTimePickerEnd.Value
      Dim tsDiff As TimeSpan = dateEnd - dateStart
      Dim intYears As Integer = Math.Floor((tsDiff.Days / 365))
      Dim intCalcYears As Integer = (intYears * 365)
      Dim intMonths As Integer = Math.Floor((tsDiff.Days - intCalcYears) / 30)
      Dim intDays As Integer = tsDiff.Days - intCalcYears - (intMonths * 30)

      MessageBox.Show(String.Format("Years={0} Months={1} Days={2}",
            intYears, intMonths, intDays))
   End Sub
End Class

Edited 4 Years Ago by thines01: typo

Why would you go in fixed days per year/month, when the above solution will return actual years/months? ie. Jan 1st to March 1st how many months is it? To make it even worse Jan 1st 2011 - March 1st 2011 vs Jan 1st 2012 - March 1st 2012 should return the same result in months or not?

This article has been dead for over six months. Start a new discussion instead.