How to Calculate the difference between two dates - vb.net-2010

I have this code:
Private Sub CalculateBUT_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateBUT.Click
If SelectTheDateComboBox.Text = "Calculate the difference between two dates" Then
FromYearTextBox.Text = FromDateTimePicker.Value.Year
FromMonthTextBox.Text = FromDateTimePicker.Value.Month
FromDayTextBox.Text = FromDateTimePicker.Value.Day
ToYearTextBox.Text = ToDateTimePicker.Value.Year
ToMonthTextBox.Text = ToDateTimePicker.Value.Month
ToDayTextBox.Text = ToDateTimePicker.Value.Day
Dim DaysMyString, MonthsMyString, YearsMyString As String
Dim DaysDifferance, MonthsDifferance, YearsDifferance As Long
DaysMyString = FromDateTimePicker.Value.Day
MonthsMyString = FromDateTimePicker.Value.Month
YearsMyString = FromDateTimePicker.Value.Year
DaysDifferance = DateDiff(DateInterval.Day, ToDateTimePicker.Value.Day, CDate(DaysMyString))
MonthsDifferance = DateDiff(DateInterval.Month, ToDateTimePicker.Value.Month, CDate(MonthsMyString))
YearsDifferance = DateDiff(DateInterval.Year, ToDateTimePicker.Value.Year, CDate(YearsMyString))
DifferenceTextBox2.Text = DaysDifferance & "Days, " & MonthsDifferance & "Months, " & YearsDifferance & "Years"
End Sub
and my problem in the picture below :
so, i need some help please.

You want DateDiff to give you the number of days between two dates and you want DaysDifference to hold the result, and that's fine:
DaysDifferance = DateDiff(DateInterval.Day, x, y)
But for this to work x and y need to be dates.
When you take ToDateTimePicker.Value (which is a date) and add .Day on the end it's no longer date.
So you want:
DaysDifferance = DateDiff(DateInterval.Day, ToDateTimePicker.Value, CDate(DaysMyString))

Related

Adding 1 everytime i use button vb.net

Basically, I need 2 make a student number and after every new entry I put the student number should +1 so 20182(or 3 if male)001 will be 20182(or 3 if male)002 after I push the button and it must keep +1 but once it reaches the 10th registered student the format changes to 20182(3 if male)010.
I have done everything but make the number +1 every time I use the button
so basically the answer must be:
Student Number is 20182001
Surname , Name
contact details
but, I done everything besides the 001, 002,003 till 010 part so if anybody could help I would be thankful
Public Class Form1
Public Number As Integer = 2018000
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strSurname As String
Dim strFullName As String
Dim strContact As String
Dim strGender As String
Dim x As Integer
'IF statement'
If Me.cboGender.SelectedItem = "Female" Then
Number = 2018300
Else
End If
If Me.cboGender.SelectedItem = "Male" Then
Number = 2018200
Else
End If
'Finding The Student Number'
Dim i As Integer = 0
Do While (i < 1)
i = i + 1
Loop
If i = 201820010 Then
Number = 201800
Else
If i = 201830010 Then
Number = 201800
End if
End If
'Add Items To ListBox'
ListBox1.Items.Add("Student number: " & Number & i)
ListBox1.Items.Add(txtSurname.Text & " , " & txtFullName.Text)
ListBox1.Items.Add(txtContact.Text)
ListBox1.Items.Add("============================================")
End Sub
End Class
Not sure what your code was doing, but based on your requirements:
Public baseFemale As Integer = 20182000
Public baseMale As Integer = 20183000
Public autoNumber As Integer = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Number as Integer;
autoNumber = autoNumber + 1
If Me.cboGender.SelectedItem = "Female" Then
Number = baseFemale + autoNumber
Else
Number = baseMale + autoNumber
Else
'Add Items To ListBox'
ListBox1.Items.Add("Student number: " & Number & i)
ListBox1.Items.Add(txtSurname.Text & " , " & txtFullName.Text)
ListBox1.Items.Add(txtContact.Text)
ListBox1.Items.Add("============================================")
End Sub
Additionally you may want to check for autoNumber exceeding 999 - but I leave that as an exercise for you.

Crystal Report Always prompting for Date Parameter

I am currently having a problem whilst passing date parameters from vb.net to Crystal Report XI
I have written a number of reports and have never had a problem whilst passing a parameter, but having said that this is the first time that I have passed a date
It appears to completely ignore the parameters that I am passing and continually asks me to enter a start date(SDate) and end date(EDate)
here is my code
Public Sub GenerateInvoiceByDate(ByVal SDate As Date, ByVal EDate As Date, ByVal boolByAccount As Boolean, ByVal strAccountRef As String)
Dim strSelectionText As String = ""
Dim theReport As New ReportDocument
theReport.FileName = strReportLocation & "Invoice2.rpt"
theReport.SetParameterValue("SDate", Format(SDate, "dd/MM/yyyy"))
theReport.SetParameterValue("EDate", Format(EDate, "dd/MM/yyyy"))
theReport.SetParameterValue("AccountRef", strAccountRef)
If boolByAccount = True Then
'generate an invoice for a specific customer account between two dates
strSelectionText = "{InvoiceHeader.CustomerRef}= {?AccountRef} and {InvoiceHeader.CreatedOn} in {?SDate} to {?EDate}"
Else
'generate all invoices between two dates
strSelectionText = "{InvoiceHeader.CreatedOn} in {?SDate} to {?EDate}"
End If
theReport.RecordSelectionFormula = strSelectionText
theReport.SetDatabaseLogon(strDatabaseUser, strDatabasePassword)
ReportView.CRView.ReportSource = theReport
ReportView.ShowDialog()
End Sub
I was assuming that the problem was with the format of the date that Crystal reports was expecting, hence i introduced that Format() method. I have confirmed that crystal is expecting a date and not date time. The two dates are passed to the method via the following code
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
CropTrackMod.GenerateInvoiceByDate(dtpSDate.Value, dtpEDate.Value, chkByAccount.Checked, txtAccountRef.Text)
End Sub
I am starting to run out of ideas and would appreciate anyone who can shed light on my problem.
Thanks in advance guys
UPDATE:
I have now changed my code as follows. If i set a start date and end date then it works OK. When i attempt to set an account ref when boolaccount = true i get the prompt for "AccountRef". I just cant understand why it keeps loosing that one value.
here is my updated code
'Test Sub for adding parameter fields to crystal reports dynamicly
Public Sub TESTGenerateInvoiceByDate(ByVal SDate As DateTime, ByVal EDate As DateTime, ByVal boolByAccount As Boolean, ByVal strAccountRef As String)
Dim strSelectionText As String = ""
Dim theReport As New ReportDocument
theReport.FileName = strReportLocation & "Invoice2.rpt"
'theReport.Load(strReportLocation & "Invoice2.rpt")
ReportView.CRView.ReuseParameterValuesOnRefresh = True
If boolByAccount = True Then
theReport.SetParameterValue("SDate", SDate)
theReport.SetParameterValue("EDate", EDate)
theReport.SetParameterValue("AccountRef", strAccountRef.ToUpper.ToString)
'theReport.SetParameterValue("Changed", "True")
'theReport.SetParameterValue("InvoiceRef", "")
'theReport.SetParameterValue("New", "True")
'generate an invoice for a specific customer account between two dates
strSelectionText = "{InvoiceHeader.CustomerRef} = {?AccountRef} and {InvoiceHeader.CreatedOn} >= {?SDate} and {InvoiceHeader.CreatedOn} <= {?EDate}"
Else
theReport.SetParameterValue("SDate", SDate)
theReport.SetParameterValue("EDate", EDate)
theReport.SetParameterValue("AccountRef", "")
'theReport.SetParameterValue("AccountRef", strAccountRef)
'theReport.SetParameterValue("Changed", "True")
'theReport.SetParameterValue("InvoiceRef", "")
'theReport.SetParameterValue("New", "True")
'generate all invoices between two dates
strSelectionText = "{InvoiceHeader.CreatedOn} >= {?SDate} and {InvoiceHeader.CreatedOn} <= {?EDate}"
End If
theReport.RecordSelectionFormula = strSelectionText
ReportView.CRView.ReportSource = theReport
theReport.SetDatabaseLogon(strDatabaseUser, strDatabasePassword)
'ReportView.CRView.Refresh()
ReportView.ShowDialog()
End Sub
If i insert a breakpoint at the end of the sub on the showdialog i can see that the "HasRecords" property of the report document has a value of "HasRecords = {"Missing parameter values."}"
I have confirmed in the report designer that there are only 3 parameter fields
I can confirm that if i enter a value manually when the report viewer prompts the report does work.
I am glad to say that i have now resolved the problem i was having above
it was due to the order in which i was setting properties of the Report Document
I needed to supply the record select formula prior to setting the parameter values
my working code is as follows
Public Sub GenerateInvoiceByDate(ByVal SDate As DateTime, ByVal EDate As DateTime, ByVal boolByAccount As Boolean, ByVal strAccountRef As String)
Dim strSelectionText As String = ""
Dim theReport As New ReportDocument
theReport.FileName = strReportLocation & "Invoice2.rpt"
'theReport.Load(strReportLocation & "Invoice2.rpt")
ReportView.CRView.ReuseParameterValuesOnRefresh = True
If boolByAccount = True Then
'generate an invoice for a specific customer account between two dates
strSelectionText = "{InvoiceHeader.CustomerRef} = {?AccountRef} and {InvoiceHeader.CreatedOn} >= {?SDate} and {InvoiceHeader.CreatedOn} <= {?EDate}"
theReport.RecordSelectionFormula = strSelectionText
theReport.SetParameterValue("SDate", SDate)
theReport.SetParameterValue("EDate", EDate)
theReport.SetParameterValue("AccountRef", strAccountRef.ToUpper.ToString)
theReport.SetParameterValue("Changed", "True")
theReport.SetParameterValue("InvoiceRef", "")
theReport.SetParameterValue("New", "True")
Else
'generate all invoices between two dates
strSelectionText = "{InvoiceHeader.CreatedOn} >= {?SDate} and {InvoiceHeader.CreatedOn} <= {?EDate}"
theReport.RecordSelectionFormula = strSelectionText
theReport.SetParameterValue("SDate", SDate)
theReport.SetParameterValue("EDate", EDate)
theReport.SetParameterValue("AccountRef", "")
theReport.SetParameterValue("AccountRef", strAccountRef)
theReport.SetParameterValue("Changed", "True")
theReport.SetParameterValue("InvoiceRef", "")
theReport.SetParameterValue("New", "True")
End If
ReportView.CRView.ReportSource = theReport
theReport.SetDatabaseLogon(strDatabaseUser, strDatabasePassword)
'ReportView.CRView.Refresh()
ReportView.ShowDialog()
End Sub
Good luck and tanks to all that helped
You probably are passing string values to a date parameter.
change this line :
theReport.SetParameterValue("SDate", Format(SDate, "dd/MM/yyyy"))
with:
theReport.SetParameterValue("SDate", SDate)

Insertion sort and taking related arrays with it

I need a bit of help with this insertion sort, The code I have so far is this:
Private Sub SortedList_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim currentitem As Integer = 2
While currentitem <= numitems
currentdataitem = frmEntry.starname(currentitem)
comparison = 1
finish = False
While comparison < currentitem And finish = False
If currentdataitem < frmEntry.starname(comparison) Then
shuffleitem = currentitem
While shuffleitem > comparison
frmEntry.starname(shuffleitem) = frmEntry.starname(shuffleitem - 1)
shuffleitem = shuffleitem - 1
End While
frmEntry.starname(comparison) = currentdataitem
finish = True
End If
comparison = comparison + 1
End While
currentitem = currentitem + 1
End While
arrayindex = 0
For Me.arrayindex = 1 To numitems
lstsorted.Items.Clear()
lstsorted.Items.Add(frmEntry.starname(arrayindex))
lstsorted.Items.Add(frmEntry.DOB(arrayindex))
lstsorted.Items.Add(frmEntry.rank(arrayindex))
Next
End Sub
This insertion sorts their names, but I also need to take their DOB and their rank with it, at what point in my visual basic code do I put this?
You can move the corresponding elements of DOB and Rank whenever you move the elements of starname.

How can I compare two times in VB.net

I want to compare two times in VB.net:
I have 1:42:21 PM and I want it to compare with TimeOfDay in VB.net how can I do that?
New DateTime(1, 1, 1, 13, 42, 21) > TimeOfDay
Or you can enclose a DateTime expression in # signs:
TimeOfDay > #1:42:21 PM#
Show the time difference in hours, minutes and seconds
Dim TimeEnd As DateTime = #5:00:00 PM#
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim span As System.TimeSpan = TimeEnd.TimeOfDay - DateTime.Now.TimeOfDay
Label1.Text = span.Hours & "hr:" & span.Minutes & "min:" & span.Seconds & "sec"
End Sub
You'd work out the format of your input time, and then call the ToString() method on your vb.net object, putting the same format in.
So for example, if your input format is h:mm:ss tt as it appears to be in your case, one method would be to do:
Dim compareTime As String = "1:42:21 PM"
If compareTime = DateTime.Now.ToString("h:mm:ss tt") Then
' The times match
End If
If you want to do some kind of comparison, you should use the DateTime.Parse() function to convert your input date into a DateTime object. Then you can simply use the > or < signs:
Dim myCompareTime As DateTime = DateTime.Parse("1:42:21 PM")
If myCompareTime.TimeOfDay > DateTime.Now.TimeOfDay Then
' Compare date is in the future!
End If
The following sample function can be used to compare time
Function comTime()
Dim t1 As Integer = DateTime.Now.TimeOfDay.Milliseconds
Dim t2 As Integer = DateTime.Now.AddHours(1).Millisecond
If (t1 > t2) Then
MessageBox.Show("t1>t2")
ElseIf (t1 = t2) Then
MessageBox.Show("t1=t2")
Else
MessageBox.Show("t2>t1")
End If
End Function
is it something along the lines of this that you are looking for?
To compare the time portion of two DateTime values:
Dim TimeStart as DateTime = #1:42:21 PM#
Dim TimeEnd as DateTime = #2:00:00 PM#
If TimeStart.TimeOfDay < TimeEnd.TimeOfDay Then
Console.WriteLine("TimeStart is before TimeEnd")
End If
Dim MyDate As DateTime = Convert.ToDateTime(MyDateAsString)
Dim MyFractionOfDay As Double = MyDate.TimeOfDay.TotalDays
The question is still valid in 2022. After extracting time as a fraction of day, it can be compared, or used to visualize progress through the day.

For loop skipping rows in DataSet

My Application uses For...Next loops to read a spreadsheet into a DataSet and then display information from it based on the results of search conditions (search term and a date range).
I'm having a problem with the data where, if I run a search that should return the first 400 rows in the spreadsheet, I'm only getting around 200 results. I know the search should return the 400 rows because I checked it in the spreadsheet before running the search.
I think my problem might be caused by my date comparisons. I think the problem might be that I'm comparing String value, so if anyone can show me a more efficient way of comparing dates, then that'll be great.
Here's my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If ListBox1.Items.Count <> 0 Then : ListBox1.Items.Clear() : End If
Dim j As Integer = 0
If TextBox1.Text.Length = 4 Then
For i As Integer = 0 To CallData.Tables(0).Rows.Count - 1
'MsgBox(CallData.Tables(0).Rows(i)(2) & " - FROM( " & DateTimePicker1.ToString & " ) TO( " & DateTimePicker2.ToString & " )")
If CallData.Tables(0).Rows(i)(3).ToString = TextBox1.Text _
And CallData.Tables(0).Rows(i)(2).ToString > DateTimePicker1.Value.ToString _
And CallData.Tables(0).Rows(i)(2).ToString < DateTimePicker2.Value.ToString Then
ListBox1.BeginUpdate()
ListBox1.Items.Add(CallData.Tables(0).Rows(i)(2).ToString)
ListBox1.EndUpdate()
j = j + 1
End If
Next
Label1.Text = j & " records found."
End If
End Sub
When you compare strings to each other it doesn't have anything to do with dates, it compares them alphabetically.
You can just cast the object from the row to a date and then compare.
Change:
CallData.Tables(0).Rows(i)(2).ToString > DateTimePicker1.Value.ToString
CallData.Tables(0).Rows(i)(2).ToString < DateTimePicker2.Value.ToString
to:
CType(CallData.Tables(0).Rows(i)(2), DateTime) > DateTimePicker1.Value
CType(CallData.Tables(0).Rows(i)(2), DateTime) < DateTimePicker2.Value
Btw, I'm no vb expert but I guess this code should do the trick :-)