0

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.

JL.
  • 78,954
  • 126
  • 311
  • 459

4 Answers4

3

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
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

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
  • 2,671
  • 5
  • 24
  • 25
  • very useful indeed, thanks for posting, good reference material, but doesn't quite solve my problem. – JL. Nov 16 '09 at 09:19
  • 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 Nov 16 '09 at 09:30
0

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"));
Igal Tabachnik
  • 31,174
  • 15
  • 92
  • 157
0

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900