How to display DateTime with selected parts of a date, but in the order of FormatProvider?

I want to display the date in the order in which it is supported, but with those elements that I only want.

The DateTime.Tostring () method has a list of templates that are very useful , but I would really like to change it.

The CultureInfo used in the following code is selected as an example: I don't want to rely on a specific CultureInfo list, if possible

var now = DateTime.Now; string nowString = now.ToString("m", CultureInfo.GetCultureInfo("en-us")); Console.WriteLine(nowString); nowString = now.ToString("m", CultureInfo.GetCultureInfo("fr-FR")); Console.WriteLine(nowString); 

displays:

April 12th
12 avril

I need a template that displays the abbreviation of the month and day, but which keeps the correct order from the specified CultureInfo. using the template "MMM dd ", the abbreviation of the month will always be displayed, and then the day, for example, violating the French order.

Any way to achieve this without much custom code?

+4
source share
1 answer

Microsoft is obviously accepting a "date to be formatted as follows:

 DateTime date1 = new DateTime(2008, 8, 29, 19, 27, 15); Console.WriteLine(date1.ToString("ddd d MMM", CultureInfo.CreateSpecificCulture("en-US"))); // Displays Fri 29 Aug Console.WriteLine(date1.ToString("ddd d MMM", CultureInfo.CreateSpecificCulture("fr-FR"))); // Displays ven. 29 août 

So don’t think that the Framework has looked at something for your business.

You need to find a workaround like this:

 private string GetCultureMonthDay(CultureInfo culture, DateTime date) { return string.Format(culture, "{0:" + culture.DateTimeFormat.MonthDayPattern.Replace("MMMM", "MMM") + "}", date); } 

using:

 ?Console.WriteLine(GetCultureMonthDay(CultureInfo.GetCultureInfo("fr-FR"), now)); 12 avr. ?Console.WriteLine(GetCultureMonthDay(CultureInfo.GetCultureInfo("en-US"), now)); Apr 12 
+1
source

Source: https://habr.com/ru/post/1306691/


All Articles