How to find Date difference in VB.NET. In this article, we will understand How to find date differences in Visual Basic (VB.NET)
If we want to find how many days are in between any two of the given dates or simply we can say the difference between the two dates can be calculated by some methods that are predefined in VB.Net.
In Visual Basic (VB) by calling any of the overloads of the DateTime constructor will allow you to specify specific elements of the date and time value like the year, month, or day.
Dim newDate As New DateTime(2000, 5, 1)
Here newDate represents year as 2000 and month as of May and date as 1.
A calculation using a DateTime structure, such as Add or Subtract, does not modify the value of the structure. Instead, the calculation returns a new DateTime structure whose value is the result of the calculation.
DateTime.Add(): In VB.Net DateTime.Add returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.
DateTime.Subtract():The DateTime.Subtract method is used in order to find the date-time difference between two instances of the DateTime method.
Dim diff As System.TimeSpan = secondDate.Subtract(firstDate)
You can also find the difference between the two dates using the following method:
Dim diff2 As String = (secondDate - firstDate).TotalDays.ToString()
VB.NET Program to find Date difference
Public Class Form1 Dim firstdate As Date Dim seconddate As Date Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click firstDate= Me.DateTimePicker1.Value.ToShortDateString secondDate=Me.DateTimePicker2.Value.ToShortDateString Dim diff As System.TimeSpan = secondDate.Subtract(firstDate) Dim diff1 As System.TimeSpan = secondDate - firstDate Dim diff2 As String = (secondDate - firstDate).TotalDays.ToString() MsgBox(diff2.ToString()) End Sub End Class
Calculate the difference between two dates using Function in VB.NET
The function below is to calculate the difference between two days. The result will be in days, and it can be zero if the two days are the same.
Function calculateDiffDates(ByVal StartDate As DateTime, ByVal EndDate As DateTime) As Integer Dim diff As Integer diff = (EndDate - StartDate).TotalDays Return diff End Function
In this way, we can calculate the difference between the two dates.