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 :-)

## All 6 Replies

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, _
days.Text = DateDiff(DateInterval.Day, _
hours.Text = DateDiff(DateInterval.Hour, _
)), _End.Value)``````

Sometimes Excel logic can do wonders.

commented: Good attention to the request! +9

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``````

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?

You're right.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.