Calculate Difference Between Two Date in VB.Net

Discussion in 'Visual Basic [VB]' started by pradeep, Mar 26, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    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:
      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.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice