So basically, I'm having this error: Error image link
Normally I would accept that my code is wrong and fix it, but the thing is it appears to be working most of the time. And I can't find the difference between cases. Why is '04-09-2018' working fine as a date but '17-08-2019' is being taken as a String?
This code takes the date from a cell in a datagridview where the date is temporary stored using a format from a database:
Private Sub wrty_show()
Dim dt As Date : Dim difd As String
dt = DataGridView1.CurrentRow.Cells(3).Value
difd = DateDiff("d", dt, Today)
If (difd >= 365) Then : Label11.Text = "Invalid" : Label11.ForeColor = System.Drawing.Color.Red
ElseIf (difd < 365) Then : Label11.Text = "Valid" : Label11.ForeColor = System.Drawing.Color.Green
End If
End Sub
And here is part of the query I use to retrieve the date from my database into the datagridview cell, with the special format to show (Somehow I get the idea that this turns the Date into a String but I'm not 100% sure because I don't have that much experience working with dates):
DATE_FORMAT(w.wrty_date , '%d-%m-%Y') AS wrty_date
I know that the format is related to the error, because I tested the program without it and it worked just fine. But the format is necessary, and if it would be the main cause that would just make every Item end up in an Error not just some of them. I figured some workaround myself of course, but I wanna know why the error is not definitive and shows up sometimes, and since it's my first question here I don't know many of the rules yet, so I apologize for anything out of place or lack of proper information. If I'm missing something please tell me and I'll update the info.
Why is '04-09-2018' working fine as a date but '17-08-2019' is being taken as a String?
Because the date format of current thread culture is running as "mm-dd-yyyy" so when you try to assing "04-09-2018" the system is able to convert it in 9th April 2018, but when you try to assign "17-08-2019" system is not able to convert it to date.
Try the below code
Private Sub wrty_show()
Dim dt As Date : Dim difd As String
dt = DateTime.ParseExact(DataGridView1.CurrentRow.Cells(3).Value, "dd-MM-yyyy", CultureInfo.InvariantCulture)
difd = DateDiff("d", dt, Today)
If (difd >= 365) Then : Label11.Text = "Invalid" : Label11.ForeColor =
System.Drawing.Color.Red
ElseIf (difd < 365) Then : Label11.Text = "Valid" : Label11.ForeColor =
System.Drawing.Color.Green
End If
End Sub