Calculate Difference Between Two Date in VB.Net

pradeep's Avatar author of Calculate Difference Between Two Date in VB.Net
This is an article on Calculate Difference Between Two Date in VB.Net in Visual Basic [VB].
Rated 4.50 By 2 users
Developers often deal with various date calculations in applications. If you need a simple way to figure out how many days there are between two given dates, consider using VB.NET's TimeSpan object.

Snippet A shows how you can use the TimeSpan object to obtain the elapsed amount of time between two dates. Then you will use the Subtract method to find the actual number of days between the two dates.

Snippet A
Code: VB
Private Sub DetermineNumberofDays()
          Dim dtStartDate As Date = "1/1/2007"
          Dim tsTimeSpan As TimeSpan
          Dim iNumberOfDays As Integer
          Dim strMsgText As String
          tsTimeSpan = Now.Subtract(dtStartDate)
          iNumberOfDays = tsTimeSpan.Days
          strMsgText = "The total number of days elapsed since " & dtStartDate.ToShortDateString() & " is: " & iNumberOfDays.ToString()
  End Sub
Notes about the example

We set a start date with a Date variable, dtStartDate, and set its value to January 1, 2007. We also declared other variables we will use, including: tsTimeSpan as a TimeSpan object, iNumberOfDays as an Integer, and strMsgText as a String. We set the value of the tsTimeSpan variable to the difference between current date/time and the value of dtStartDate.

In order to calculate the number of days between current date/time (Now) and the dtStartDate, we use the TimeSpan object's Days property and set its value to iNumberOfDays. Then we create a text that we will show in a message box by concatenating necessary text and variables in setting the value for strMsgText. The last step is displaying the value of strMsgText in a Message box.