C # Date Parse Exact Issue

The following code is causing an error, any ideas why?

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

Error: The string is not recognized as a valid date and time.

0
source share
4 answers

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") , expected by the ParseExact function.

+3
source

You can 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 compare the format with the common one in the Czech Republic. You must use CultureInfo to do this:

 string properDate = DateTime.Now.ToString(new CultureInfo("cs-CZ")); 
0
source

Does your local date culture indicate "dd.MM.yyyy HH: mm: ss"? Simple: if the ToString() date does not create this layout, then it will not be ParseExact cleanly - and ParseExact not very forgiving.

I am wondering if you really want to call:

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

All Articles