How to Get a Time Interval in VB.NET
Submitted by janobe on Tuesday, May 13, 2014 - 14:55.
Today, I’m going to teach you how to get a time interval in VB.NET. In here, I use the TimeSpan properties for getting the time interval. It segregates the hours, minutes, seconds, millisecond and even the tick of the clock. Then it will appear in each corresponding text boxes.
I used Microsoft Visual Studio for creating this application.
Let’s begin:
Open Microsoft Visual Studio, create a new Project then name it “TimeInterval” and do the Form just like this.
Go to the solution explorer and click the view code.
In the code view, create a sub procedure for separating the time intervals of the corresponding fields.
After that, do this following code in the
Then, do this following code on the first load. It sets the value of the end time higher than the starting time.
Finally, press F5 to run your project.
Output:
- Private Sub TimeInterval(ByVal ts As TimeSpan)
- 'USE THE PROPERTIES OF THE TIMESPAN AND IT DEMONSTRATE TimeSpan.Hours
- ', TimeSpan.Milliseconds , TimeSpan.Minutes , TimeSpan.Seconds
- ' AND TimeSpan.Ticks
- Try
- txthours.Text = ts.Hours.ToString
- txtmillisecond.Text = ts.Milliseconds.ToString
- txtminutes.Text = ts.Minutes.ToString
- txtseconds.Text = ts.Seconds.ToString
- txtticks.Text = ts.Ticks.ToString
- Catch ex As Exception
- MessageBox.Show(ex.Message, Me.Text)
- End Try
- End Sub
click
event of the Button to get the time interval.
- Private Sub btngo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btngo.Click
- Try
- 'CREATE A VARIABLE OF A TIMESPAN
- Dim time_span As TimeSpan
- 'CREATE THE VARIABLE OF A DATETIME
- Dim strt_Date As DateTime
- Dim end_Date As DateTime
- 'SET AND CONVERT THE TIME FROM THE DATETIMEPICKER
- strt_Date = DateTime.Parse(dtpstrTime.Text)
- end_Date = DateTime.Parse(dtpEndtime.Text)
- 'SUBTRACT THE STARTING TIME AND THE END TIME
- time_span = end_Date.Subtract(strt_Date).Duration
- 'PERFORM THE SUB PROCEDURE THAT YOU HAVE
- 'CREATED IN DISPLAYING THE TIME INTERVAL
- TimeInterval(time_span)
- Catch Ex As Exception
- MessageBox.Show(Ex.Message, Me.Text)
- End Try
- End Sub
- Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
- 'SET THE VALUE OF THE END DATE HIGHER THAN THE START DATE
- End Sub
Add new comment
- 1044 views