user2146538
user2146538

Reputation: 344

Format Exception - string not recognized as a valid DateTime

I have an issue similar to this > Format exception String was not recognized as a valid DateTime

However, my spec requires a date format of ddMMyyyy, therefore I have modified my code but I am still getting the same error

 DateTime now = DateTime.Now;
 DateTime dt = DateTime.ParseExact(now.ToString(), @"ddMMyyyy", CultureInfo.InvariantCulture);

I am unclear why.

Upvotes: 0

Views: 875

Answers (4)

codemonkeh
codemonkeh

Reputation: 2152

You code fails because you are attempting to parse a date in the format ddMMyyyy, when by default DateTime.ToString() will produce a format with both date and time in the current culture. For myself in Australia that would be dd/MM/yyy hh:mm:ss p e.g. 11/10/2013 11:07:03 AM

You must realise is that the DateTime object actually stores a date as individual components (e.g. day, month, year) that only needs to be format when you output the value into whatever format you desire. E.g.

DateTime now = DateTime.Now;
string formattedDate = now.ToString("ddMMyyyy", DateTimeFormatInfo.InvariantInfo);

For more information see the api doc: http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx

Upvotes: 1

Dweeberly
Dweeberly

Reputation: 4777

now.ToString() does not return a string formatted in that way. Try using now.ToString("ddMMyyyy"). You might be better off testing with a static string like "30041999"

Upvotes: 1

Brian Ball
Brian Ball

Reputation: 12596

Debug your code and look at what the result of now.ToString() is, it's is not in the format of "ddMMyyyy", which is why the parse is failing. If you want to output now as a string in the ddMMyyy format, then try now.ToSTring("ddMMyyyy") instead.

Upvotes: 1

Samuel Neff
Samuel Neff

Reputation: 74909

For ParseExact to work, the string coming in must match exactly the pattern matching. In the other question you mentioned, the text was coming from a web form where the format was specified to be exactly one format.

In your case you generated the date using DateTime.Now.ToString() which will not be in the format ddMMyyyy. If you want to make the date round trip, you need to specify the format both places:

DateTime now = DateTime.Now;
DateTime dt = DateTime.ParseExact(now.ToString("ddMMyyyy"), @"ddMMyyyy", CultureInfo.InvariantCulture);

Upvotes: 1

Related Questions