Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set day and month format, but not their order

Tags:

c#

datetime

I know about Datetime formats. "dd" stands for day from 01 to 31, "MM" - the month from 01 through 12. I need this format. But if I write "dd MM"(in my case in ToString() method) it will always put day before the month. How can I set this format(dd and MM) without changing the order(what comes first - day or month) from current locale? So if in current culture day comes first I want to receive "20 08 2012"(separator doesn't matter here), and if month comes first - "08 20 2012"

like image 250
Alecs Avatar asked Aug 20 '12 13:08

Alecs


People also ask

Why are dates not formatting correctly in Excel?

Imported Dates Are Text Data Although the entries in column C look like dates, Excel sees them as text, not real dates. And that's why the imported dates won't change format -- Excel will not apply number formatting to text.

How do I rearrange date format?

Press CTRL+1. In the Format Cells box, click the Number tab. In the Category list, click Date, and then choose a date format you want in Type.

How do I reorder date and month in Excel?

In the Format Cells dialog box, please click Custom in the Category box under Number tab. If the original date formatting is m/d/yyyy, please enter d/m/yyyy into the Type box, and if the original date formatting is d/m/yyyy, please enter m/d/yyyy into the Type box, and finally click the OK button.


2 Answers

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

var mdp = CultureInfo.CurrentCulture.DateTimeFormat.MonthDayPattern;
string pattern = mdp.IndexOf('M') < mdp.IndexOf('d') ? "MM dd" : "dd MM";
like image 65
Sergey Kalinichenko Avatar answered Sep 17 '22 21:09

Sergey Kalinichenko


Have a look at the culture's MonthDayPattern. Maybe you can customize it to your needs, e.g.

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"
like image 20
dtb Avatar answered Sep 19 '22 21:09

dtb