Skip to content

Solving the String was not recognized as a valid DateTime problem the hard way.

March 23, 2012

String was not recognized as a valid DateTime.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: String was not recognized as a valid DateTime.

————————————————————————————————————-

Who has seen this error before? I am sure plenty of you have seen it time and time again.

Most of the later part of the day of 1-2 hours was spent looking into why this is occuring.

I know from experience is that the formatting of the date time is not correct in the way the system wants it to be interpreted based on the InvariantCulture Setting, and its a real pain. I would think that the database is storing it in UK settings for dates and .NET is interpreting the date as US, grrr!!

You would think that the code below would solve the problem where GatheredFromDatabase() is a datetime string in UK format: –

txtTime.Text = GatheredFromDatabase();
string format = “MM/dd/yyyy hh:mm:ss”;
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
provider = new System.Globalization.CultureInfo(“en-US”);
DateTime result = DateTime.ParseExact(txtTime.Text, format, provider);

txtTime.Text = Convert.ToDateTime(result).ToString();

But it throws the above error!!

It is a pain as I have used different variations on the above code and it has worked when changing the date time but in this instance VS doesn’t intepret the date time or even recognise it?

A quick fix although not the best solution was to do this which swaps the first two parts of the data around: –

txtTime.Text = txtTime.Text.Remove(0, 3).Insert(3, txtTime.Text.Substring(0, 2) + “/”);

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: