user1055487
user1055487

Reputation: 261

calculate the difference between two dates to display as a number in days (VB)

How do I calculate the difference between two dates to display as a number in days?

I have 2 text boxes (txtHStart_Date & txtHEnd_Date) I have used an Ajax Calendar Extender to enter the dates in each of these text boxes. I would like to get the difference between these two dates to show in a seperate text box (txtNoOfDays)

I've seen the timespan function but can seem to get this to work. I'm not to sure how to declare the text boxes as the dates I would the calculation to be made from

Code:

Dim D1 As Date
Dim D2 As Date
Dim ts As New TimeSpan
D1 = txtHStart_Date.Text
D2 = txtHEnd_Date.Text
ts = D2 - D1

But I know this isn't right. I also don't know how to get it to display in the 3rd TextBox.

Upvotes: 1

Views: 14219

Answers (3)

x0n
x0n

Reputation: 52480

Use the DateDiff function:

http://msdn.microsoft.com/en-us/library/b5xbyt6f(v=vs.80).aspx

"Returns a Long value specifying the number of time intervals between two Date values."

Upvotes: 0

Jim H.
Jim H.

Reputation: 5579

The TimeSpan is simple to use.

Dim dtStart As DateTime = DateTime.Now.AddDays(-100)
Dim dtEnd As DateTime = DateTime.Now

Dim ts As TimeSpan = dtEnd - dtStart
Console.WriteLine(ts.TotalDays)

Edit:

And going by the comment you added where you assign a text string to a date variable, you would be better off using (and handling)

DateTime.TryParse("some date string", dtStart)

TryParse returns a boolean success/fail so you can react to whether you were given good/bad data.

Upvotes: 2

Alvin
Alvin

Reputation: 995

This is the best I know so far. StringToDate function let's you decide what date format you want to use.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        txtHStart_Date.Text = "11/20/2011"
        txtHEnd_Date.Text = "11/25/2011"

        Dim dtHStart_Date As DateTime = StringToDate(txtHStart_Date.Text, "MM/dd/yyyy")
        Dim dtHEnd_Date As DateTime = StringToDate(txtHEnd_Date.Text, "MM/dd/yyyy")

        Dim span As TimeSpan = dtHEnd_Date.Subtract(dtHStart_Date)
        txtNoOfDays.Text = span.Days
    End If
End Sub

Public Function StringToDate(ByVal strDate As String, ByVal pattern As String)
    Dim myDTFI As New System.Globalization.DateTimeFormatInfo()
    myDTFI.ShortDatePattern = pattern
    Dim dtDate As DateTime
    Try
        dtDate = DateTime.Parse(strDate, myDTFI)
    Catch ex As Exception
        Return False
    End Try
    Return dtDate
End Function

Upvotes: 0

Related Questions