SanthoshKumar SanthoshKumar - 9 months ago 54 Question

String was not recognized as a valid DateTime in ParseExact

When I try to convert the

to a specific format i'm getting this error.

DateTime.Now= 6/5/2013 2:29:21 PM

DateTime.ParseExact(CStr(DateTime.Now), "MM/dd/yyyy", CultureInfo.CurrentCulture)


String was not recognized as a valid DateTime

Why i'm getting this?

Answer Source

Apart from the fact that you're converting a DateTime to a string then back again, the DateTime format doesn't match exactly.

DateTime.ParseExact parses a string into a DateTime object, and the format you provide it must match exactly. You said that DateTime.Now appears as 6/5/2013 2:29:21 PM, for which the correct format is M/d/yyyy h:mm:ss tt. Check MSDN for more information on custom date formats.

I'm going to go out on a limb and say that, by looking at your code, I think you are trying to format the date into just the date, which can be achieved using the ToString method on DateTime:

string todaysDate = DateTime.Now.ToString("MM/dd/yyyy"); // todaysDate will contain "06/05/2013"