This code formats a date string entered by the user, adding slashes and correct number of year digits and converts it to a proper date format. You can use the following code to make your user interface more friendly. It will help you in correcting and preventing mistakes over what date is entered. Also the user will be able to immediately see what your program is going to accept and correct if necessary.
Just add the code given below to your form class to create a function to format the date. |
Click here to copy the following block | Private Function StringToDate(ByRef DateString As String) As Boolean
If InStr(DateString, "-")=0 And InStr(DateString, "/") = 0 InStr(DateString, "\") = 0 Then If DateString.Length = 4 Then DateString = DateString.Substring(0,2) & "/" & DateString.Substring(2) ElseIf (DateString.Length = 6 Or DateString.Length = 8) Then DateString = DateString.Substring(0,2) & "/" & DateString.Substring(2,2)_ & "/" & DateString.Substring(4) End If
End If
Try DateString = Format(Convert.ToDateTime(DateString), "MM/dd/yyyy") Return True
Catch e as Exception Return False End Try |
To use it in your forms, add the following code to the Leave event of your text box. |
When u run it, enter some dates using 2 digit years and dashes instead of slashes and as you tab from it, the date will be reformatted nicely, providing confirmation to the user. |
|