.Net 5 DateTime.ParseExact problems

Viewed 387

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?

2 Answers

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.

It's a breaking change in .NET 5 where Globalization APIs use ICU libraries on Windows. To keep the old behaviour, you can add the following to the .csproj file

<ItemGroup>
  <RuntimeHostConfigurationOption Include="System.Globalization.UseNls" Value="true" />
</ItemGroup>

Other options are set the "System.Globalization.UseNls" on the runtimeconfig.json

{
  "runtimeOptions": {
     "configProperties": {
       "System.Globalization.UseNls": true
      }
  }
}

or setting the environment variable DOTNET_SYSTEM_GLOBALIZATION_USENLS to true or 1.

Related