A Coder
A Coder

Reputation: 3046

String was not recognized as a valid DateTime in ParseExact

When I try to convert the DateTime 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)

Error:

String was not recognized as a valid DateTime 

Why i'm getting this?

Upvotes: 1

Views: 24358

Answers (3)

Sean Airey
Sean Airey

Reputation: 6372

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"

Upvotes: 7

Buh Buh
Buh Buh

Reputation: 7546

6/5/2013 2:29:21 PM is not the same as MM/dd/yyyy.
So of course the parse fails.

From your comments it sounds like you are really testing the format string, and you don't care about the value of the date. So why not just hard code your date in the format you really want:

String userInput = "MM/dd/yyyy";
DateTime.ParseExact("11/11/2011", userInput,  CultureInfo.CurrentCulture)

Upvotes: 2

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391456

Note the part of the method named Exact, you're giving it a string containing a time, and does not specify how to parse the time, so the parsing will fail.

Try this:

DateTime.ParseExact(str, "M/d/yyyy h:mm:ss tt", CultureInfo.CurrentCulture)

Example LINQPad program:

void Main()
{
    Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");

    string str = "6/5/2013 2:29:21 PM";

    DateTime.ParseExact(str, "M/d/yyyy h:mm:ss tt", CultureInfo.CurrentCulture).Dump();
}

Output:

6/5/2013 2:29:21 PM

Upvotes: 1

Related Questions