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"
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.
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.
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.
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";
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With