views:

38

answers:

1

I want to display the date in the order that the culture provides, but with the elements I want only.

The DateTime.Tostring() method has a list of patterns that are very useful but I would like a very small change in it.

The CultureInfo used in the following the following code are chosen as example, I don't want to rely on a specific list of CultureInfo, 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 12
12 avril

I would like a pattern that display the abbreviation of the month and the day, but that keeps the correct order from the specified CultureInfo. using the pattern "MMM dd" will always display the month's abbreviation first, followed by the day, breaking the french order for example.

Any way to achieve that without too much custom code?

+1  A: 

apparently, Microsoft "accepts" the date to be formatted like this:

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 Framework previewed something for your case.

You will 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);
}

usage:

?Console.WriteLine(GetCultureMonthDay(CultureInfo.GetCultureInfo("fr-FR"), now));
12 avr.

?Console.WriteLine(GetCultureMonthDay(CultureInfo.GetCultureInfo("en-US"), now));
Apr 12
serhio
That's what I figured out and the reason of my question on SO. :)If no better solution, I will settle for "MMM d"
Stephane
see the update.
serhio
nice! thanks for the trick. I wonder if it would be possible to implement this as a IFromatProvider for the ToString method, and have it completely transparent somehow :). But that's already a great solution to my problem :) thanks
Stephane
notice that this method presumes that the MonthDayPattern contain `MMMM`. For Fr and En, and probably for a lot of cultures this works. but there could be other cases.
serhio