Why this line of code sometimes throws System.FormatException
?
DateTime d = DateTime.ParseExact("01.07.2014", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Because your string and format doesn't match.
From documentation;
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.
Use dd.MM.yyyy
format instead.
DateTime d = DateTime.ParseExact("01.07.2014",
"dd.MM.yyyy",
CultureInfo.InvariantCulture);
Here a demonstration
.
Remember, "/"
custom format specifier has a special meaning in custom date and time formats. It means as; replace me with the current culture date separator.
In your profile, it says you are from Azerbaijan. That means your CurrentCulture
is probably az-Cyrl-AZ
(Cyrillic, Azerbaijan) or az-Latn-AZ
(Latin, Azerbaijan).
Actually, doesn't matter which culture you use on this case because both culture has .
as a DateSeparator
property.
That means your original code also works with your CurrentCulture
.
DateTime d = DateTime.ParseExact("01.07.2014",
"dd/MM/yyyy",
CultureInfo.CurrentCulture);
// or you can use null
For more information, take a look;
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