I'm trying to convert the retrieved string of date from access database to become date type to do the calculation of months. The problem i'm having is unable to convert the retrieved string type variable to date type. I tried a few methods such as Convert.ToDateTime, DateTime.ParseExact().. still fails
My code is able to retrieve a column of the permitEndDate as string but unable to convert it to date type cause i need to pass it to my function.
Please help cause i'm new in VB and many thanks to those who read my questions.
My code:
For i As Integer = 0 To ds.Tables("lecturer").Rows.Count - 1
TextBox1.AppendText(ds.Tables("lecturer").Rows(i).Item(16) & vbCrLf)
'convert string to date type
Dim getDate As String = ds.Tables("lecturer").Rows(i).Item(16)
TextBox1.AppendText("Parse getDate: " & getDate & vbCrLf)
Dim expDate As DateTime = DateTime.ParseExact(getDate, "dd/MM/yyyy", CultureInfo.InvariantCulture)
TextBox1.AppendText("Parse expDate with date type: " & expDate & vbCrLf)
' Dim permitEndDate As String = ds.Tables("lecturer").Rows(i).Item(16)
'expDate = Convert.ToDateTime(permitEndDate)
' TextBox1.AppendText("Difference in month: " & CalculateMonth(expDate) & vbCrLf)
Next
The function :
'calculation of months
Function CalculateMonth(ByVal endDate As Date) As Integer
Dim result As Integer
'1.get today date
Dim currentDate As Date = Date.Now.ToString("dd/MM/yyyy")
'calculation formula
result = DateDiff(DateInterval.Month, currentDate, endDate)
Return result
End Function
So, my error "String was not recognized as a valid DateTime." the line is : Dim expDate As Date = Date.ParseExact(getDate, "dd/MM/yyyy", CultureInfo.InvariantCulture)
Date/Timedata type so why not use that? - jmcilhinneyDim currentDate As Date = Date.Now.ToString("dd/MM/yyyy"). Why would you convert aDateto aStringand then expect it to be implicitly converted back to aDate? If what you want is today's date with the time zeroed then you should be usingDate.Today. - jmcilhinneyDate/Timedata type in Access. I would suggest using aDateTimePickeror equivalent control but even if you use aTextBox, the correct thing to do would be to validate the user's input and convert it to aDatefirst and then save that to the database. You can useDate.TryParseto do both the validation and the conversion. You should fix your database now and then your current issue simply goes away. - jmcilhinney