var date= DateTime.ParseExact("16-03-2022 1:30", "dd-MM-yyyy HH:mm", CultureInfo.InvariantCulture);
When I enter 16-03-2022 13:30, it does not give an error but when the parameter is 16-03-2022 1:30, I get an error, how can I solve it?
CodePudding user response:
I feel like taking a risk to answer but..
Let's go step by step. One of the good things about .NET methods is that you can see what exceptions can be thrown on that method in their documentation.
From "Exception" section on documentation it says;
FormatException
s
orformat
is an empty string.-or-
s
does not contain a date and time that corresponds to the pattern specified informat
.-or-
The hour component and the AM/PM designator in
s
do not agree.
Your s
or format
is not empty, your string does not have any AM or PM designator, so the only option left is "s
does not contain a date and time that corresponds to the pattern specified in format
." as a reason.
Also from documentation, it says;
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
What "format" we are talking about? There are two of them. Custom date and time format strings and Standard date and time format strings. Since we are using DateTime.ParseExact
, we need to consider using custom date and time format.
Let's look at all parts can be parse in your 16-03-2022 1:30
string;
- 16 --> Two digit day number (
dd
) - 03 --> Two digit month number with leading zero (
MM
) - 2022 --> Four digit year (
yyyy
) - 1 --> One digit hour (it can be
h
orH
because there is no time designator in your string and we can't know it's in 12-hour clock format or 24-hour clock format) - 30 --> Two digit minutes (
mm
)
So, the proper format of your 16-03-2022 1:30
string can be either dd-MM-yyyy H:mm
or dd-MM-yyyy h:mm
which depends on you. If it is 24-hour format, use H
specifier, if it is 12-hour format, use h
specifier.
CodePudding user response:
When you see the word "Exact" in ParseExact()
, it means it. Any deviation from the expected format at all will cause an exception.
In this case, the HH
specifier is not an exact match for the 1
value for the hour. It would match if you had 01
instead, but just 1
isn't the same thing. To match the hours without leading zeros you need a single H
, creating this format string:
dd-MM-yyyy H:mm
This will still match later hours like "10" and "11". Additionally, the capital "H" instead of lower-case means it still expects 24-hour time, so numbers like "13" up to "23" still work, too.