vb.nettimeelapsed

VB Elapsed time method confusion


I have to code a program which finds the elapsed time when i enter the 2 times into 2 textboxes, one textbox will be the start time, the other textbox will be the end time, I am lost as to how I do this.

Example
Start time is 12:45
the end time is 13:15
then the elapsed time should be 30 minutes


Public Class Form1 

    Dim starttime As DateTime 
    Dim endtime As DateTime 
    Dim timetaken As TimeSpan 
    Private Sub btnOK_Click(sender As Object, 
        e As EventArgs) Handles btnOK.Click 
        starttime = txtStart.Text 
        endtime = txtEnd.Text 
    End Sub 

End Class

Solution

  • Quickly out of my head:

    Option Strict On 'every good programmer does this
    
    Public Class Form1 
    
        Private starttime As DateTime 'Please use Dim only in functions or subs
        Private endtime As DateTime 
        Private timetaken As TimeSpan 
    
        Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click 
            starttime = DateTime.Parse(txtStart.Text) 'Parse the string input
            endtime = DateTime.Parse(txtEnd.Text)
            timetaken = endtime - starttime
        End Sub 
    
    End Class
    

    Of course this highly depends on what string can be parsed into a DateTime instance. It even depends on your systems culture. Have a look at https://msdn.microsoft.com/en-us/library/System.DateTime.Parse(v=vs.110).aspx for more details about how an input string should look like. If days would be enough, you could use a DatePicker control instead (which however sadly doesn't support your need for times).

    You can supply a format of the input string with DateTime.ParseExact afaik

    To catch errors when a string input in the textboxes could not be parsed, use DateTime.TryParse.