Home > Back-end >  Formatting Date with abbreviated month, while adhering to culture date structure
Formatting Date with abbreviated month, while adhering to culture date structure

Time:10-13

Developing a multilanguage application, and trying to format a DateTime object to string within a limited space in a table. Full month names might be too long, so we have to use abbreviations.

Some cultures have the format "Oct 12", some have "12. okt" and so on.

The standard .ToString("m") is almost what I want, but with abbreviations: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings#MonthDay

Similar question, but the answer won't work for us, as this dictates the order of month and day: Formatting Date String abbreviating month

Is there any way of getting the overall structure of a culture's date formatting, like order of day and month, with or without "." after the number etc? Or another way of generating the required string? This feels like it should be fairly straight forward, as all the pieces are already present.

CodePudding user response:

As per the documentation you linked, the custom date and time format "m" is defined by a CultureInfo's DateTimeFormat.MonthDayPattern property. So I'd look that up for the current culture and customize the format string. Then use the modified format string with ToString.

CodePudding user response:

I was able to solve this myself using the culture's DateTimeFormat wich provides a MonthDayPattern. By simply replacing "MMMM" with "MMM" this will solve the challenge, at least for the locales that we plan to support. I have not tested with all possible locales.

(I know it won't work for "ja-JP", wich has special characters in their pattern)

DateTime date = DateTime.Now;
CultureInfo culture = new("en-US", false);

DateTimeFormatInfo dateTimeFormat = culture.DateTimeFormat;
string pattern = dateTimeFormat.MonthDayPattern.Replace("MMMM", "MMM");
string formatted = date.ToString(pattern, culture);

The pattern for "en-US" goes from "MMMM d" to "MMM d" giving "Oct 13"

The pattern for "nb-NO" goes from "d. MMMM" to "d. MMM" giving "13. okt."

  • Related