Calculate Number Of Days Between Two Dates in VB.NET
Here, we will see how To calculate Number Of Days Between Two Dates.
Introduction
This is Simple Way Of calculating Number Of Days Between Two Dates . User Can Select Two
Dates By DateTimePicker and He Can Calculate Number Of Days. For This, Take a Window Form ,
Two Labels , Two DateTimePicker and a Button. Then Set the Properties Of These Controls as ,
Label
Set Its Name as Start Date and End Date by it's Text Property.
DateTimePicker
Set its Format Property as Short.
Button
Set its Name as Calculate By its Text Property. Then Form Will Look Like below figure1.
Figure1
After This Write The Following Code On Double Click Of Calculate Button.
Private Sub btnCalculate_Click(sender As System.Object, e As System.EventArgs)Handles btnCalculate.Click
If True Then
Dim dt1 As DateTime = Convert.ToDateTime(DateTimePicker1.Text)
Dim dt2 As DateTime = Convert.ToDateTime(DateTimePicker2.Text)
Dim ts As TimeSpan = dt2.Subtract(dt1)
If Convert.ToInt32(ts.Days) >= 0 Then
MessageBox.Show("Total Days are " & Convert.ToInt32(ts.Days))
Else
MessageBox.Show("Invalid Input")
End If
End If
End Sub
Then, Select Two Dates And Click Calculate Button, The Result Will Look Like This.
Figure2
If User Does Wrong Entry ,Means If End Date Comes Before Start Date , Then Error Message
Will Show as "Invalid Input". Like as below.
Figure3