14,545,215 members
Rate this:
See more:
I developed a program where I have two text boxes named start date and end date. Another textbox is for total number of days. The user selected start in calendar as well as end date. What I need is for system to calculate number of days based on selection from calender. I have code that I tried but does not work properly. For example, if the event is for one day (say 17 May 2020 to 17 May 2020)it will give total number of days zero instead of one. I attached the code I tried.

What I have tried:

```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
txtDays.Text = Convert.ToInt32(ts.Days)

Else
MessageBox.Show("Start date cannot be older than end date", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If```
Posted
Updated 17-May-20 9:15am
Richard MacCutchan 16-May-20 11:49am

That is correct, there are zero days between 17 May and 17 May. If you want to include the first (or last) day, then add 1 to the total. Also do not use `Convert.ToInt32` everywhere, especially for values that are already integer types.
NyikoB 18-May-20 1:45am

Thanks it works by simply adding 1

Rate this:

## Solution 2

You don't need while-wend loop (solution #1).

Take a look at this:
```Dim d1 As DateTime = New DateTime(2020, 5, 1)
DIm d2 As DateTime = DateTime.Today()

Dim result = (d2-d1).TotalDays
Console.WriteLine(result)```

For further details, please see: TimeSpan Struct (System) | Microsoft Docs[^]
v2
Rate this:

## Solution 1

Here is a function that works for me
```Private Function GetNumDays (StartDate As Date, EndDate As Date ) As Integer
Dim NumDays As Integer = 0
While StartDate < EndDate
NumDays+=1
End While

Return NumDays
End Function ```