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

on Aug 16, 2019 03:46 AM

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)



Download FREE API for Word, Excel and PDF in ASP.Net: Download
on Aug 16, 2019 04:11 AM

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.


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);


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