Search code examples
c#.net.net-core.net-5datetime-parsing

.Net 5 DateTime.ParseExact problems


Just migrated on .Net 5.
The next code returns "01/01/0001 00:00:00 +00:00" in "date" variable.

DateTime.TryParseExact(
    "Июн 16 2021",
    "MMМ d yyyy",
    CultureInfo.CreateSpecificCulture("ru-RU"),
    DateTimeStyles.None,
    out DateTime date
);

https://dotnetfiddle.net/E5VDbH

Facing no problem on .Net Core 3.1.

Has anyone run into the same problem?


Solution

  • I went in the same direction as @PMF and printed out all the month names for the ru-RU culture. From that I could see that there is no month abbreviation that matches what you have in your example. Here's how to get all the valid values:

    var ci = CultureInfo.CreateSpecificCulture("ru-RU");
    Console.WriteLine(String.Join(" - ", ci.DateTimeFormat.AbbreviatedMonthNames));
    

    Seeing as we're in June I suspect Июн is also supposed to be June, which in .NET 5 is abbreviated as июнь.

    I don't read or write Russian so I don't know how these compare to what you're expecting, but that's at least what .NET 5 is expecting.

    When I replaced Июн with июнь in your example it correctly parsed it as a date.

    You could've seen this if you had used DateTime.ParseExact() and surrounded your code in a try/catch. You would've got an exception that told you:

    String 'Июн 16 2021' was not recognized as a valid DateTime.

    Which could've pointed you in the right direction.