Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I find the days/months/years between two dates

How to

How can I find the days/months/years between two dates

by  Rolliee  Posted    (Edited  )
Write a global function as shown below:

The return value is Years: ?? Months: ?? Days: ?? with the prober values instead of '??'

This handles leap years by using the built in functions of VB.

Public Function DateDiff2(ByVal d1 As Date, ByVal d2 As Date) As String
Dim d3 As Date, nDays As Integer
Dim d1Day As Integer, nDayStart As Integer
Dim nYears As Integer, d1Mon As Integer, MonLast As Integer, nn As Integer, nMon As Integer, d1Year As Integer

If d1 > d2 Then
d3 = d1
d1 = d2
d2 = d3
End If

d1Day = Day(d1)
d1Mon = Month(d1)
d1Year = Year(d1)
nn = 0
nMon = 0
nDays = 0
nYears = 0

MonLast = d1Mon
Do While d2 > d1
d1 = d1 + 1
nn = nn + 1

nDays = nDays + 1

If (Day(d1) = d1Day) And Month(d1) <> MonLast Then
nMon = nMon + 1
nDays = 0
MonLast = Month(d1)
If nMon = 12 Then
nMon = 0
nYears = nYears + 1
End If
End If
Loop


DateDiff2 = "Years: " & Format(nYears, "00") & " Months: " & Format(nMon, "00") & " Days: " & Format(nDays, "00")
End Function
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top