String was not recognized as a valid DateTime

This seems to be a problem that people encounter often so here is a post on how to avoid it.

Assume you are trying to convert a string to a DateTime object like below:

DateTime DT= DateTime.Parse(your_datetime_string);

Then there is good chance that you will see “String was not recognized as a valid DateTime” error. ┬áHere DateTime.Parse will try to use the current culture info and formatting, to override this you can use ParseExact method, provide it with a format string and culture info (here I use “null” which means current culture). I doubt if culture will make any difference once you provide the formatting string.

Below method can get you out of trouble:

DateTime DT= DateTime.ParseExact(your_datetime_string, "dd.MM.yyyy H:mm:ss", null);


Here “dd.MM.yyyy H:mm:ss” is the format that I use for DateTime stringifying, use yours accordingly.

Hope this helps someone.

Good luck,
Serdar.

Leave a Reply

Your email address will not be published. Required fields are marked *