Set the format of the day and month, but not their order

I know about Datetime formats. "dd" means the day from 01 to 31, "MM" - the month from 01 to 12. I need this format. But if I write "dd MM" (in my case in the ToString () method), it will always put a day to a month. How can I set this format (dd and MM) without changing the order (what comes first - day or month) from the current locale? So if on the current day of culture the first comes, I want to get "20 08 2012" (the separator is not important here), and if the month comes first - "08 20 2012"

+7
source share
2 answers

You can use MonthDayPattern from the current locale to get the relative order of these two elements, and then build either dd MM or MM dd :

 var mdp = CultureInfo.CurrentCulture.DateTimeFormat.MonthDayPattern; string pattern = mdp.IndexOf('M') < mdp.IndexOf('d') ? "MM dd" : "dd MM"; 
+5
source

Take a look at the culture of MonthDayPattern . Perhaps you can customize it to your needs, for example.

 string FormatWithMonthDayPattern(DateTime dateTime, CultureInfo cultureInfo) { var pattern = cultureInfo.DateTimeFormat.MonthDayPattern; return dateTime.ToString(Regex.Replace(pattern, "M+", "MM")); } var result1 = FormatWithMonthDayPattern(DateTime.Now, new CultureInfo("en-US")); // result1 == "08 20" var result2 = FormatWithMonthDayPattern(DateTime.Now, new CultureInfo("fr-FR")); // result2 == "20 08" 
+3
source

All Articles