Domanda

Is there any way to Display the difference between 2 different times. I currently have 2 buttons.

Sub AddButtonClick(sender As Object, e As EventArgs)

    StartTime.Text = DateTime.Now.ToString()

End Sub

This generates the first timestamp

Sub EndBreakClick(sender As Object, e As EventArgs)

    EndTime.Text = DateTime.Now.ToString()

    DateDiff(DateInterval.Minute, Endtime, StartTime)
End Sub

This generates the second timestamp but the datediff line causes the app to crash as soon as I press the button.

È stato utile?

Soluzione

You can rely on TimeSpan:

Dim elapsedTime As TimeSpan = DateTime.Parse(EndTime.Text).Subtract(DateTime.Parse(StartTime.Text))

It behaves as a normal time variable from which you can extract all the information you want. Example:

Dim elapsedMinutesText As String = elapsedTime.Minutes.ToString()

Bear in mind that the code above takes string variables as inputs (the text from your textboxes) because it performs the corresponding conversion: Convert.ToDateTime.

Regarding your code, it refers to EndTime and StartTime and these are not DateTime variables, but TextBoxes. You have to convert them (their text) into DateTime as I am doing above, that is:

DateDiff(DateInterval.Minute, DateTime.Parse(EndTime.Text), DateTime.Parse(StartTime.Text))

Altri suggerimenti

The DateDiff function will do it.

label1.text = DateDiff("n", DateTime.Parse(EndTime.Text), DateTime.Parse(StartTime.Text)).ToString

If your app is crashing, did you check the variable you tried to pass to it? It looks like your trying to pass the textbox to it and not the textbox.text.

Sub EndBreakClick(sender As Object, e As EventArgs)

    EndTime.Text = DateTime.Now.ToString()

    Dim myStartTime As DateTime? = If(DateTime.TryParse(StartTime.Text, myStartTime), myStartTime, Nothing)
    Dim myEndTime As DateTime? = If(DateTime.TryParse(EndTime.Text, myEndTime), myEndTime, Nothing)
    If myStartTime.HasValue AndAlso myEndTime.HasValue Then
        Dim someVariable As Long = DateDiff(DateInterval.Minute, myStartTime.Value, myEndTime.Value)
        ' DO SOMETHING WITH THAT VARIABLE HERE
    Else
        ' One or both of the textbox values wasn't a valid DateTime.  Display an error message or something
    End If
End Sub
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top