Calculating the Years Between Dates

Thursday Mar 18th 2004 by Karl Moore
Share:

Business applications often find it useful to calculate the number of years between two particular dates, such as the date a customer first ordered and the present date, perhaps to see whether they apply for a "loyalty" discount or a free gift.

Business applications often find it useful to calculate the number of years between two particular dates, such as the date a customer first ordered and the present date, perhaps to see whether they apply for a "loyalty" discount or a free gift.

Don't scramble in the code window. Just use my next little snippet. Simply call YearsBetweenDates, passing in a start date and end date. It'll return an Integer containing the number of full years between the specified dates:

```Public Function YearsBetweenDates(ByVal StartDate As DateTime, _
ByVal EndDate As DateTime) As Integer
' Returns the number of years between the passed dates
If Month(EndDate) < Month(StartDate) Or _
(Month(EndDate) = Month(StartDate) And _
(EndDate.Day) < (StartDate.Day)) Then
Return Year(EndDate) - Year(StartDate) - 1
Else
Return Year(EndDate) - Year(StartDate)
End If
End Function
```

Karl Moore (MCSD, MVP) is an experience author living in Yorkshire, England. He is author of numerous technology books, including the new Ultimate VB .NET and ASP.NET Code Book (ISBN 1-59059-106-2, \$49.99), plus regularly features at industry conferences and on BBC radio. Moore also runs his own creative consultancy, White Cliff Computing Ltd. Visit his official Web site at www.karlmoore.com.

Share:
Home
Mobile Site | Full Site