Parsing DateTime

I am trying to parse this datetime, but always returns false.

DateTime.TryParseExact("07/01/2007 12:15", "mm/dd/yyyy HH:mm", new CultureInfo("en-US"), DateTimeStyles.None, out met) 
+4
source share
2 answers

Template for the month capital MM :

 "MM/dd/yyyy HH:mm" 

MM means minutes, and you already used it at the end.

+21
source

The problem is that at runtime, it finds two components of minutes in a given line, as indicated in the format for parsing. Thus, you cannot construct a valid DateTime object from a given input string with the specified format. He finds 07 and 15 both in minutes and in problem.

When you run code with ParseExact and without TryParse, you will receive the following exception.

System.FormatException: DateTime pattern 'm' appears more than once with different values.

Solution . Please note that mm is in minutes, mm - for several months. In your particular case, you need to indicate which part of the month and which part are minutes. Assuming you need 07 as a month, Here's an adjusted version of your code.

 DateTime.TryParseExact("07/01/2007 12:15", "MM/dd/yyyy HH:mm", new CultureInfo("en-US"), DateTimeStyles.None, out met) 
+6
source

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


All Articles