Datediff() function not getting the expected result in VB.NET - 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.

Related

Getting all the dates between two selected dates

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.

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

How to calculate positive difference between time from two DateTimes

I am having two date time picker start time and end time.I have to calculate difference between time from this end time and start time.And also how to check am or pm for calculating time difference.
I have tried this by using timespan. It gives me right answer,but when I select time suppose as 12:58:02 in end time and 10:57:05 in start time, it gives me wrong answer like -599. I want to know how to convert this negative difference to positive.
I have tried with the following code:
Dim startTime As Date
Dim endTime As Date
startTime = Convert.ToDateTime(dtpOpStTime.Value)
endTime = Convert.ToDateTime(dtpOpETime.Value)
Dim diff As System.TimeSpan
diff = endTime - startTime
actualTime = Convert.ToString(Int32.Parse(diff.Hours.ToString()) * 60 + Int32.Parse(diff.Minutes.ToString()))
ucTime.TxtCode.Text = actualTime
my another issue is as follows:
I am having 4 date time picker,2 for showing start date and end date and 2 for start time and end time.so when i changed date timespan getting is wrong .so how to resolve this.
I have tey with the following code:
Dim span As TimeSpan = dtpOpEDate.Value - dtpOpStdate.Value
Dim span1 As TimeSpan = dtpOpETime.Value - dtpOpStTime.Value
Dim duration As TimeSpan = span.Duration()
Dim duration1 As TimeSpan = span1.Duration()
Dim durDay As Int32 = duration.Days
Dim durHr As Int32 = duration1.Hours
Dim durMin As Int32 = duration1.Minutes
Dim totalDur = durDay * 24 * 60 + durHr * 60 + durMin
actualTime = totalDur.ToString()
ucTime.TxtCode.Text = actualTime
Problem is through this I am getting wrong time difference ,when i change suppose start time 10:51:02 PM and end time to 3:51:04 AM and start date to 25-Mar-2014 and End date to 26-Mar-2014 then difference should be 5 hours though the day change but i am getting wrong difference
A difference between two DateTimes returns a TimeSpan object. You can either use the Subtract method of DateTime or even use -. You have to use the subtract the earlier date from the later date:
Dim span As TimeSpan = dtpEnd.Value - dtpStart.Value
You can use the Duration method to get an absolute timespan, then the order doesn't matter:
Dim duration As TimeSpan = (dtpStart.Value - dtpEnd.Value).Duration()
If you for example want the number of minutes between, use the TotalMinutes property:
Dim minutes As Int32 = CInt(duration.TotalMinutes)

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

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