Getting all the dates between two selected dates - vb.net

Good afternoon, I'm new to programming and I'm working with VB.NET.
I need to get the difference between two dates and then list all the intermediate dates in listbox1. I tried the following code but it doesn't work.
Private Sub breaks()
Dim date1 As Date = DateTimePicker1.Value.ToString("dd/MM/yyyy")
Dim date2 As Date = DateTimePicker2.Value.ToString("dd/MM/yyyy")
While date1 <= date2
Dim result = date1
ListBox1.Items.Add(result)
Dim term = 1
date1 = DateTimePicker1.Value.AddDays(term)
End While
End Sub
The function is called within a button. When executed it only shows the sidebars but is blank.
The image shows start date 03/10/2020 and end date 03/16/2020, however the result (listbox) does not return anything.
I expected my result to come:
03/10/2020
03/11/2020
03/12/2020
03/14/2020
03/15/2020
03/16/2020
the interval between them.
Can anyone tell me what's wrong?

You can use some linq for a simple solution
ListBox1.DataSource =
Enumerable.Range(0, 2 + DateTimePicker2.Value.Subtract(DateTimePicker1.Value).Days).
Select(Function(offset) DateTimePicker1.Value.AddDays(offset)).
ToList()
It generates a list of numbers to act as the offset from the initial date, then adds them the specified number of times (different between the dates in days) to create all the dates. No loop required.
Credit to this answer
Edit:
This can also be similarly applied to a DataGridView, but in order to make a single column, we would need to select an anonymous type.
DataGridView1.DataSource =
Enumerable.Range(0, 2 + DateTimePicker2.Value.Subtract(DateTimePicker1.Value).Days).
Select(Function(offset) New With {.Date = DateTimePicker1.Value.AddDays(offset)}).
ToList()

You should avoid using strings for datetimes until they need to be text.
The variable date1 can be used for all the dates, like this:
Dim date1 As Date = DateTimePicker1.Value
Dim date2 As Date = DateTimePicker2.Value
While date1 <= date2
ListBox1.Items.Add(date1.ToString("MM/dd/yyyy"))
Dim term = 1
date1 = date1.AddDays(term)
End While
Also, you should make sure to set Option Strict On as the default for new projects, and set it for the current project.

Related

Excel dates table intersection with VBA

I have one excel page and I store date type datas. This datas extra workdays and plus holidays in every year. Other table in this page has start and end date. I would like to show some interval the employees work days. I would like to use the VBA. How to solved this problem?
Use NETWORKDAYS.INTL()
=NETWORKDAYS.INTL(E2,F2,1,A2:A3)
This pictures the Excel table and my code:
Dim startDate As Date
Dim endDate As Date
Dim retValue As Integer
Dim days As Variant
Dim dates As Variant
days = Worksheets("Tényleges munkanapok").ListObjects("TáblázatKorrekciósNapok").DataBodyRange.Value
dates = Worksheets("Tényleges munkanapok").ListObjects("TáblázatSzámoló").DataBodyRange.Value
Dim i As Integer
Dim actualDate As Date
startDate = days(1, 1)
actualDate = dates(1, 1)
Dim CountVariant As Integer
CountVariant = UBound(days)
i = 0
Do While i <= CountVariant
If startDate < actualDate Then
i = i + 1
End If
Loop

VBA: How to make an IF statement on a DateDiff function

In a VBA project i'm working on, I need to count the number of lines where the difference between two dates is inferior to X hours.
My idea was to go through all the lines and check for each line, like this:
Dim count as Integer
if DateDiff("h", date1, date2) < 24 then
count = count + 1
End If
The problem is that I get an incompatibility type error (execution error 13).
Is it possible to make IF statements on a DateDiff function? Or is it maybe possible to make a filter with DateDiff as the condition?
Thanks for the help and sorry for my poor english as it's not my main language!
I have tested it like this without any errors.
Dim date1 As Date
Dim date2 As Date
date1 = "14/10/2015 19:00:00"
date2 = "14/10/2015 16:28:43"
If DateDiff("h", date1, date2) < 24 Then
count = count + 1
End If
The VBA conversion function CDate can apply a little of the overhead you constantly pay for to correct the dates. With that said, it is best to correct the data to begin with and not rely upon error controlled conversion functions.
Dim date1 As Date, date2 As Date, n As Long
date1 = CDate("14/10/2015 19:00:00")
date2 = CDate("14/10/2015 16:28:43")
Debug.Print date1 & " to " & date2
If IsDate(date1) And IsDate(date2) Then
If DateDiff("h", date1, date2) < 24 Then
n = n + 1
End If
'alternate
If date2 - date1 < 1 Then
n = n + 1
End If
End If
Given that 24 hours is a day and a day is 1, simple subtraction should be sufficient for this base comparison.
Your DMY format may cause problems with the EN-US-centric VBA in date conversion. If an ambiguous date string is found (e.g. "11/10/2015 16:28:43") you may find that you are interpreting it as MDY.

Concatenating variables

I'm trying to create an expiration date using values selected from drop down lists on my web form, however I am unable to concatenate the Month variable value and Year variable value. I get the error: Error Operator '&' is not defined for types 'String' and System.Web.UI.WebControls.ListItem'. I have tried to use the "+" also but get the same error.
Here is the code I have:
Dim Month = monthDropDownList.SelectedValue
Dim Year = yearDropDownList.SelectedItem
Dim MonthYear = Month & Year
Dim ExpirationDate As Date = MonthYear
Any help would be greatly appreciated.
You don't want SelectedItem. You want SelectedValue. You should also explicitly declare your variables. You also can't create a Date in this manner. You need to use integers.
Dim Month As Integer= Convert.ToInt32(monthDropDownList.SelectedValue)
Dim Year as Integer = Convert.ToInt32(yearDropDownList.SelectedValue)
Dim ExpirationDate As Date = New Date(Year, Month, 1)
As a slight "cleaner" way to do this I would use:
Dim Month as Integer
Dim Year As Integer
Dim ExpirationDate As Date
Integer.TryParse(monthDropDownList.SelectedValue, Month)
Integer.TryParse(yearDropDownList.SelectedValue, Year)
If (Month > 0 AndAlso Year > 0) Then
ExpirationDate = New Date(Year, Month, 1)
End If

Datediff() function not getting the expected result in VB.NET

I am using the following code in my project. I want to find the number of days by given the last date and now.
Dim BorrowDate As Date
Dim i As Integer
BorrowDate = Date.Parse(txtBorrowDate.Text)
i = DateDiff(DateInterval.Day, BorrowDate, DateTime.Now)
for example, when BorrowDate is "01/Jul/2011" then the result is 7 days which it should be 10 to now. Please help
Since you are using .Net you might try this
Dim BorrowDate As Date = Date.Parse(txtBorrowDate.Text)
Debug.WriteLine(BorrowDate.ToString)
Debug.WriteLine(DateTime.Now.ToString)
Dim ts As TimeSpan = DateTime.Now - BorrowDate
Dim numdays As Integer = CInt(ts.TotalDays)
Debug.WriteLine(numdays.ToString("n0"))
edit: Init the variables and show the dates.

Dates in For Loop in vb.net

In vb.net I have two data values as shown below:
Dim startp as datetime
Dim endp as datetime
I have a function called ProcessData(soemdate) which processes dataporting.
In VB.net is there a way I can do something like
For each day between startp and endp
ProcessData(soemdate)
Next
Thanks
Here is another way to do this.
Dim startP As DateTime = New DateTime(2009, 1, 1)
Dim endP As DateTime = New DateTime(2009, 2, 1)
Dim CurrD As DateTime = startP
While (CurrD <= endP)
ProcessData(CurrD)
Console.WriteLine(CurrD.ToShortDateString)
CurrD = CurrD.AddDays(1)
End While
For Each Day As DateTime in Enumerable.Range(0, (endp - startp).Days) _
.Select(Function(i) startp.AddDays(i))
ProcessData(Day)
Next Day
Adding to Joel Coehoorn's answer which I personally think should be the accepted answer as I always try to avoid While loops no matter how safe they may appear. For...Each is a much safer approach although the enumerable isn't very pretty in-line. You can however move it to a function to keep things more readable, plus you can re-use as needed.
For Each Day As DateTime In DateRange(StartDate, EndDate)
ProcessData(Day)
Console.WriteLine(Day.ToShortDateString)
Next
Public Shared Function DateRange(Start As DateTime, Thru As DateTime) As IEnumerable(Of Date)
Return Enumerable.Range(0, (Thru.Date - Start.Date).Days + 1).Select(Function(i) Start.AddDays(i))
End Function
I also added 1 to Enumerable range since as Joel had it, it wouldn't return the end date and in my situation I needed it to return all dates in the range including the start and end days.
Enumerable.Range is a sort of loop in itself that adds i days to the startdate advancing i with each call from in this case 0 to the difference between start and end days + 1. So the first time it's called you get the result of Start.AddDays(0), next you'll get Start.AddDays(1) and so on until the range is complete.
You can easily loop through each day if you convert your dates to OLE Automation Date OADate where the left portion represents the day and the right portion represents the time.
For example #06/19/2018#.ToOADate converts to 43270.0
For loopDate As Double = #06/19/2018#.ToOADate To #07/01/2018#.ToOADate
Dim thisDate As Date = DateTime.FromOADate(loopDate)
' Do your stuff here e.g. ProcessData(thisDate)
Next
Yes, you can use an accumulator date:
Dim Accumulator as DateTime
Accumulator = startp
While (Accumulator <= endp)
Accumulator = Accumulator.AddDays(1)
End While
Not tested, and I'm a C# programmer, so be easy if my syntax is wrong.
For those that come looking later, I had to add a +1 to the Range endpoint to get this to work for when the start and end were the same. Here is the code I used.
For Each Day As DateTime in Enumerable.Range(0, (endp - startp).Days + 1) .Select(Function(i) startp.AddDays(i))
'Do work here
Next Day
Set a calendar table with all dates and query values from there.
SQL:
Select Date as MyDate from tblCalendar Where Date >= StartDt And Date <= EndDate
.NET:
While Reader.read
process(MyDate)
End While