Thursday 15 January 2009

Getting the difference between two dates

I've lost count of the number of times I've been asked to provide the difference between two dates and the equal number of times anything to do with dates as left mean tearing what's left of my hair out.

So here's a couple of useful things:

The TimeSpan Structure

Example Usage:

Get the difference in days between two dates:

Public Function GetDays(ByVal date1 As Date, ByVal date2 As Date) As Integer
Dim span As TimeSpan = date1 - date2
Return span.Days
End Function

Eg. Get number of days between now and 1st Jan 2000

GetDays(Date.Now, "01/01/00")

or alternatively we can use DateDiff

Public Function GetTheDays(ByVal date1 As Date, ByVal date2 As Date) As Integer
Return DateDiff(DateInterval.Day, date1, date2)
End Function

No comments: