tags:

views:

233

answers:

4

The following code produces an error, any ideas why?

string dateFormatString = "dd.MM.yyyy HH:mm:ss";
string properDate = DateTime.ParseExact(DateTime.Now.ToString() , dateFormatString , null ).ToString()

Error is: String is not recognised as a valid date and time.

+1  A: 

You just need this - rest is piece of cake. http://john-sheehan.com/blog/wp-content/uploads/msnet-formatting-strings.pdf

and this http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

MSIL
very useful indeed, thanks for posting, good reference material, but doesn't quite solve my problem.
JL
Hi JL - only thing here to be noted is whatever you are passing should be in the format you are trying to parse back - you are sending a default string representation of date time which isnt same as "dd.MM.yyyy HH:mm:ss" but instead it is "dd/MM/yyyy HH:mm:ss" slash and dot difference that is.
MSIL
A: 

You could simply do:

string dateFormatString = "dd/MM/yyyy HH:mm:ss";
string properDate = DateTime.Now.ToString(dateFormatString);

EDIT: According to your comments, you are trying to match the format to that common in the Czech Republic. You should use CultureInfo to do do that:

string properDate = DateTime.Now.ToString(new CultureInfo("cs-CZ"));
hmemcpy
+2  A: 

DateTime.Now.ToString() formats the date using the current culture. You need to specify the same format: DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") that's expected by the ParseExact function.

Darin Dimitrov
A: 

Does your local culture write dates as "dd.MM.yyyy HH:mm:ss" ? Simply: if the date's ToString() doesn't produce this layout, then it won't parse cleanly - and ParseExact is not very forgiving.

I'm wondering if you actually want to call:

string s = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss");
Marc Gravell