Calculate Days difference between two dates in C# and VB.Net

Last Reply one month ago By dharmendr

Posted one month ago

I have 2 text boxes and I want to calculate the amount of days between the two dates. Currently with the code below it subtracts one day from the actual amount of days that i select and I do not want that. Please assist or provide a more effective approach.

Dim dt1 As DateTime = Convert.ToDateTime(txtFrom.Text)
Dim dt2 As DateTime = Convert.ToDateTime(txtTo.Text)
Dim ts As TimeSpan = dt2.Subtract(dt1)

 

 

You are viewing reply posted by: dharmendr one month ago.
Posted one month ago

Hi Tevin,

The answer is obviously correct. Since it inclusive both dates so returns a day less in difference. So add 1 to get your result.

C#

protected void Page_Load(object sender, EventArgs e)
{
    DateTime dt1 = new DateTime(2019, 08, 01);
    DateTime dt2 = new DateTime(2019, 08, 31);
    TimeSpan ts = dt2.Subtract(dt1);
    Response.Write(ts.TotalDays + 1);
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim dt1 As DateTime = New DateTime(2019, 8, 1)
    Dim dt2 As DateTime = New DateTime(2019, 8, 31)
    Dim ts As TimeSpan = dt2.Subtract(dt1)
    Response.Write(ts.TotalDays + 1)
End Sub

Output

31