Click here to Skip to main content
15,908,843 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
Comments
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

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

Take a look at this:
VB.NET
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[^]
 
Share this answer
 
v2
Here is a function that works for me
VB
Private Function GetNumDays (StartDate As Date, EndDate As Date ) As Integer 
   EndDate = EndDate.AddDays(1) 
   Dim NumDays As Integer = 0 
   While StartDate < EndDate 
        NumDays+=1
        StartDate = StartDate.AddDays(1) 
   End While

Return NumDays
End Function 
 
Share this answer
 
Comments
maxamed ibraahim 2021 29-Oct-21 22:53pm    
88.write program requested your date of birth and compute your mercurial age

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900