4

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?

DmitryD
  • 51
  • 3
  • 2
    Try printing out all month names. Sometimes they "fix" these. – PMF Jun 17 '21 at 18:53
  • See https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo?view=net-5.0#cultureinfo-and-cultural-data . The `TryParseExact` fails most likely due to how `CultureInfo` is handled differently on .NET Core 3.1 versus .NET 5. – Rick Davin Jun 17 '21 at 19:03
  • That is expected because `DateTime.TryParseExact` returns `false` which means the operation did *not* succeed. If you were expecting an `Exception` you need to use the method `DateTime.ParseExact` (without Try). Try means return true/false based on success and do not throw an Exception. – Igor Jun 17 '21 at 19:09
  • 1
    It works when you change the text to "июнь 16 2021" – Rick Davin Jun 17 '21 at 19:15
  • @PMF, thanks for good advice ) – DmitryD Jun 17 '21 at 19:15

2 Answers2

3

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.

TheHvidsten
  • 4,028
  • 3
  • 29
  • 62
3

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.

Magnetron
  • 7,495
  • 1
  • 25
  • 41