DateTime.ToString Is not working for MMM in Swedish culture anymore

Swapnil Lomate 0 Reputation points
2023-04-21T05:59:48.34+00:00

I have issue with formatting date to dd MMM yyyy. when i try to format this date with Swedish culture I get date as 21 apr. 2023 where it should be 21 apr 2023 I tried below code in console app with .net core 7 and its same: var date = DateTime.UtcNow;
        var cultureInfo = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(c => c.LCID == 29);
        Console.WriteLine(cultureInfo.LCID);
        var dateString = date.ToString("dd MMM yyyy", cultureInfo);
        Console.WriteLine(dateString); Please note this works when i run this program in Azure app service. so there must be something with my windows 11 enterprise 21H2 operating system or I am not sure where is the issue? Any help would be appreciated

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,649 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jerry Fu - MSFT 576 Reputation points Microsoft Vendor
    2023-04-21T10:09:15.1966667+00:00

    Hi, @Swapnil Lomate .There are 2 workarounds here you can reference. They all give the "21 apr 2023" result.

    1 Simply replace the "." with empty

    var dateString = date.ToString("dd MMM yyyy", cultureInfo).Replace(".", "")
    
    

    2 Fix the AbbreviatedMonthNames and AbbreviatedMonthGenitiveNames in a new culture

       var date = DateTime.UtcNow;
       var cultureInfo = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(c => c.LCID == 29);
       cultureInfo.DateTimeFormat.AbbreviatedMonthNames = cultureInfo.DateTimeFormat.AbbreviatedMonthNames.Select(x => x.TrimEnd('.')).ToArray();
       cultureInfo.DateTimeFormat.AbbreviatedMonthGenitiveNames = cultureInfo.DateTimeFormat.AbbreviatedMonthGenitiveNames.Select(x => x.TrimEnd('.')).ToArray();
       
       var dateString = date.ToString("dd MMM yyyy", cultureInfo);
       Console.WriteLine(dateString);
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments