Problem with the DateTime.ParseExact method: always throws an exception even with the correct format

I was looking for a forum for such solutions, but could not find one that really matches my specific problem.

It may take a more experienced look to find the problem, so I appreciate all the help!

Problem: I am trying to parse a string with the date of a DateTime variable. However, even if the string date format is exactly the same, it still throws an exception.

I would like to know why and how I can solve this. I really don’t see what is wrong there!

try { string value = "Sep-17-2012 03:04:07 am"; string format = "M-dd-yyyy hh:mm:ss tt"; DateTime temp = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture); } catch(Exception e){} 

Thanks in advance,

Mad

+4
source share
3 answers

Your format should be MMM, not M http://www.dotnetperls.com/datetime-format

 string format = "MMM-dd-yyyy hh:mm:ss tt"; 

M - display a unique month number

MMM - display a three-month month

+7
source

Your format string is incorrect:

 string value = "Sep-17-2012 03:04:07 am"; string format = "MMM-dd-yyyy hh:mm:ss tt"; DateTime temp = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture); 

Ref: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

+2
source

you need MMM for a month.

 try { string value = "Sep-17-2012 03:04:07 am"; string format = "MMM-dd-yyyy hh:mm:ss tt"; DateTime temp = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture); } catch(Exception e){} 
+1
source

Source: https://habr.com/ru/post/1480526/


All Articles