Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date and Time Difference in Minutes

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.

like image 708
user2602702 Avatar asked Jan 12 '23 21:01

user2602702


1 Answers

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))
like image 148
varocarbas Avatar answered Mar 16 '23 10:03

varocarbas