Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime parsing issue

Tags:

c#

.net

datetime

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)
like image 721
developer Avatar asked Jul 21 '10 06:07

developer


People also ask

What is DateTime Parse?

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.

What is DateTime parse 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.

How do I parse a DateTime flutter?

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.


2 Answers

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.

like image 183
Darin Dimitrov Avatar answered Sep 28 '22 13:09

Darin Dimitrov


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)
like image 44
this. __curious_geek Avatar answered Sep 28 '22 12:09

this. __curious_geek