I am trying to parse this datetime, but it always return false.
DateTime.TryParseExact("07/01/2007 12:15", "mm/dd/yyyy HH:mm", new CultureInfo("en-US"), DateTimeStyles.None, out met)
The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.
Class DateTimeParseExceptionAn exception thrown when an error occurs during parsing. This exception includes the text being parsed and the error index. Implementation Requirements: This class is intended for use in a single thread. Since: 1.8 See Also: Serialized Form.
For example, "2020-01-42" will be parsed as 2020-02-11, because the last valid date in that month is 2020-01-31, so 42 days is interpreted as 31 days of that month plus 11 days into the next month. To detect and reject invalid component values, use DateFormat. parseStrict from the intl package.
The pattern for month is capital MM
:
"MM/dd/yyyy HH:mm"
mm
stands for minutes and you've already used it at the end.
The problem is that at runtime it finds two components of minutes in the given string as specified by the format for parsing. So you're not able to construct a valid DateTime object from the given input-string with format specified. It finds 07
and 15
both as minutes hence the problem.
When you run the code with ParseExact
and without TryParse, you'll get following exception.
System.FormatException: DateTime pattern 'm' appears more than once with different values.
The Solution: Note that, mm
is for minutes, MM
is for months. In your particular case, you need to tell which part is the month and which one is the minutes. Assuming you need 07
as the month, Here's the corrected version of your code.
DateTime.TryParseExact("07/01/2007 12:15", "MM/dd/yyyy HH:mm", new CultureInfo("en-US"), DateTimeStyles.None, out met)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With