how to uppercase date and month first letter of To

2020-03-03 05:24发布

问题:

currently i obtain the below result from the following C# line of code when in es-MX Culture

   Thread.CurrentThread.CurrentCulture =
     Thread.CurrentThread.CurrentUICulture = new
                CultureInfo("es-mx");

  <span><%=DateTime.Now.ToLongDateString()%></span>

miércoles, 22 de octubre de 2008

i would like to obtain the following

Miércoles, 22 de Octubre de 2008

do i need to Build my own culture?

回答1:

You don't need to build your own culture. You only need to change the property DateTimeFormat.DayNames and DateTimeFormat.MonthNames in the current culture.

i.e.

        string[] newNames = { "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo" };
        Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames = newNames;

However, it's weird that en-US show months and days with the first uppercase letter and for mx-ES not.

Hope it helps!.



回答2:

The pattern of LongDate for Spanish (Mexico) is

dddd, dd' de 'MMMM' de 'yyyy

according to Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern. I guess you just have to manually convert the initial letters of the day and month to uppercase or you can use Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase and then replace "De" with "de".



回答3:

first two Solutions works fine but what if we would like to extend this to any culture so i came up with this approach i change the current culture date time arrays into TitleCase

private void SetDateTimeFormatNames()
        {

            Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames = ConvertoToTitleCase(Thread.CurrentThread.CurrentCulture.DateTimeFormat.DayNames);
            Thread.CurrentThread.CurrentCulture.DateTimeFormat.MonthNames = ConvertoToTitleCase(Thread.CurrentThread.CurrentCulture.DateTimeFormat.MonthNames);

        }

private string[] ConvertoToTitleCase(string[] arrayToConvert)
            {
                for (int i = 0; i < arrayToConvert.Length; i++)
                {
                    arrayToConvert[i] = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(arrayToConvert[i]);
                }

                return arrayToConvert;
            }

how can this be improved with out the Loop?



回答4:

a little late but this work for me!

 public static string GetFecha()
    {
        System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("es-EC");
        System.Threading.Thread.CurrentThread.CurrentCulture = culture;

        // maldita sea!
        string strDate = culture.TextInfo.ToTitleCase(DateTime.Now.ToLongDateString());

        return strDate.Replace("De", "de");


    }