Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.ParseExact throws System.FormatException

Tags:

c#

datetime

Why this line of code sometimes throws System.FormatException?

DateTime d = DateTime.ParseExact("01.07.2014", "dd/MM/yyyy", CultureInfo.InvariantCulture);
like image 521
gdrt Avatar asked Dec 15 '22 21:12

gdrt


1 Answers

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;

  • Custom Date and Time Format Strings
like image 63
Soner Gönül Avatar answered Jan 08 '23 18:01

Soner Gönül