How to format a date as localized Short MonthDay s

2020-07-18 02:23发布

I would like to format a DateTime to a string containing the month name abbreviated and the date for use in axis labels in a graph.

The default DateTime format strings do not contain abbreviated month. I guess there is no standard but I could take a substring of the first 3 characters of the month name and replace this into the MonthDay format. The reason I would use MonthDay is that the ordering of month and date is locale dependent.

Does anyone have a better idea?

http://msdn.microsoft.com/en-us/library/az4se3k1.aspx#MonthDay

6条回答
Explosion°爆炸
2楼-- · 2020-07-18 02:50

You can pass a CultureInfo in the Date.ToString() method. Either you have a specific culture info or you can use the CultureInfo.CurrentCulture:

var date = DateTime.Now;
var ci = new CultureInfo("de-CH");
var output = date.ToString("d MMM", ci);
查看更多
叼着烟拽天下
3楼-- · 2020-07-18 02:52

Quick, easy and does the job.

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(Month).Substring(0,3);
查看更多
劫难
4楼-- · 2020-07-18 02:53

Edited: Use date.ToString("d MMM"). It will show 7 sep.

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-07-18 02:55

You can use the custom string formatters to do this:

DateTime now = DateTime.Now;
Console.WriteLine("{0}", now.ToString("ddd MMMM dd"));

See the section "How Standard Format Strings Work" on the page you linked to for more info.

查看更多
霸刀☆藐视天下
6楼-- · 2020-07-18 03:01

Here is the solution I came up with for the similar situation of wanting a localized version of 01/29:

Regex.Replace(c.DateTimeFormat.ShortDatePattern, @"(yy(yy)?[/\.\- ]|[/\.\- ]yy(yy)?)", "")

Here is the format output for all cultures, so you can see if it will work for you:

CultureInfo.GetCultures(CultureTypes.AllCultures)
    .Select(c => new {
        c.Name,
        c.DateTimeFormat.MonthDayPattern,
        c.DateTimeFormat.ShortDatePattern,
        DayMonth1 = Regex.Replace(c.DateTimeFormat.ShortDatePattern, @"[/\.\- ]?yy[/\.\- ]?", ""),
        DayMonth2 = Regex.Replace(c.DateTimeFormat.ShortDatePattern, @"(yyyy[/\.\- ]|[/\.\- ]yyyy|yy[/\.\- ]|[/\.\- ]yy)", ""),
        DayMonth3 = Regex.Replace(c.DateTimeFormat.ShortDatePattern, @"(yy(yy)?[/\.\- ]|[/\.\- ]yy(yy)?)", "")
    })
    .OrderBy(x => x.Name)
    .Dump();

The DateMonth1 replace will remove an extra padding character for a couple cultures (specifically 'bg').

查看更多
我想做一个坏孩纸
7楼-- · 2020-07-18 03:08

You could take the MonthDay pattern and replace "MMMM" with "MMM" - then apply that pattern:

string pattern = CultureInfo.CurrentCulture.DateTimeFormat.MonthDayPattern;
pattern = pattern.Replace("MMMM", "MMM");
string formatted = dateTime.ToString(pattern);

It's somewhat crude, but I believe it would work.

查看更多
登录 后发表回答