Jacob Kapitein
Jacob Kapitein

Reputation: 315

Can't convert string to DateTime in c#

Now I know this question get's asked a lot, but I keep running into the same problem with every solution I try. I am trying to convert a string in format "yyyy-MM-dd" to type DateTime, but I keep getting the following error:

Unable to cast object of type 'System.DateTime' to type 'System.String'.

The property is the following: public DateTime DateOfBirth { get; set; }

The line where I'm trying is something as follows: DateOfBirth = //Conversion happens here\\

What I have tried:

DateOfBirth = DateTime.ParseExact(reader.GetString(6), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
DateOfBirth = DateTime.ParseExact(reader.GetString(6), "yyyy-MM-dd", CultureInfo.InvariantCulture);
DateOfBirth = DateTime.ParseExact(reader.GetString(6), "yyyy-MM-dd", null);
Convert.ToDateTime("reader.GetString(6)")

Just nothing seems to work. It's propably something really stupid I'm overlooking, but I just can't seem to find the issue. Hope you guys can help?

Greetings, Jacob

Upvotes: 0

Views: 2230

Answers (3)

Jacob Kapitein
Jacob Kapitein

Reputation: 315

My god, I know it was something really stupid. I needed to use reader.GetDateTime().

I am so terribly sorry for this stupid question. I have been busy with this problem for a few hours now and just when you ask a question, you fix it. Welcome to software development I guess...

Upvotes: 3

DubDub
DubDub

Reputation: 1387

Reading your error, your actual problem is that you're trying to convert a DateTime to a string, as you say:

Unable to cast object of type 'System.DateTime' to type 'System.String'.

This isn't a problem with you converting the string to a date time, but a problem with the reader converting the datetime to a string. This is what you should be looking into. I'm unsure on what the type of your reader is, so maybe look at the docs for a 'GetDatetime' method attached to the reader. Or create one, or tell us the type of the Reader and we'll see.

Upvotes: 4

Sandris B
Sandris B

Reputation: 133

First, check what reader.GetString(6) returns?

Upvotes: 0

Related Questions