0

I want to convert datetime to string. I have declared DATE_PLACED_IN_SERVICE as datetime in SQL server database and want to convert it to string in my source code. I am getting the error: "Unable to cast object of type 'System.DateTime' to type 'System.String'"

Here my source code:

If rdmysql.IsDBNull(rdmysql.GetOrdinal("DATE_PLACED_IN_SERVICE")) = False Then
    Dim ServiceDate As Date = rdmysql.GetString(rdmysql.GetOrdinal("DATE_PLACED_IN_SERVICE"))
    ServiceTxt.Text = Format(ServiceDate, "yyyy-MM-dd")
End If

1 Answer 1

1

This column is of type datetime, so you cant use GetString but GetDateTime:

Dim ServiceDate As Date = rdmysql.GetDateTime(rdmysql.GetOrdinal("DATE_PLACED_IN_SERVICE"))

Instead of the VB6 Format function i would use .NET:

ServiceTxt.Text = ServiceDate.ToString("yyyy-MM-dd")

or simple and readable (if your culture uses - as date delimiter):

ServiceTxt.Text = ServiceDate.ToShortDateString()
Sign up to request clarification or add additional context in comments.

1 Comment

@hasni: you're welcome. Remember to accept if your question is solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.