Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Visual Basic [VB] (http://www.go4expert.com/articles/visual-basic-tutorials/)
-   -   Calculate Difference Between Two Date in VB.Net (http://www.go4expert.com/articles/calculate-difference-date-vbnet-t3609/)

pradeep 26Mar2007 15:23

Calculate Difference Between Two Date in VB.Net
 
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()
          MsgBox(strMsgText)
  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.


All times are GMT +5.5. The time now is 13:04.