简体   繁体   中英

C# datetime format that includes date/month/year and not day

I want to use a standard date format that displays date, month and year in the standard regional settings of the pc. However I could only find "D" which lists day along with Date-Month-Year. Is there any way I can remove the day from it or any other way to get my desired output?

DateTime date1 = new DateTime(2008, 4, 10);
Console.WriteLine(date1.ToString("D", 
                  CultureInfo.CreateSpecificCulture("en-US")));
// Displays Thursday, April 10, 2008   

Note: I don't want to be using custom format (d MMMM yyyy) as I want the regional settings of the order to be maintained.

you can use this for your case:

DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;
string str = (new DateTime(2008, 4, 10)).ToString(myDTFI.LongDatePattern.Replace("dddd", ""));

try this:

date1.ToString("d", CultureInfo.CreateSpecificCulture("en-US"))

It will return what you want!!

If you're using one of the standard formats, then what gets displayed is going to depend on the culture anyway - so even if you could find something which doesn't display the day of week in en-US, it may still display it in other cultures.

I suppose you could find the DateTimeFormatInfo for the culture, find its LongDatePattern and then remove any occurrence of a single "d" from that format string. It would be pretty nasty though.

您应该使用“d”而不是“D”来获得所需的输出。

Many cultures have multiple long date patterns and you can select from them the first one which lacks a day of the week pattern:

    static void Main(string[] args)
    {
        foreach (var cultureInfo in System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures))
        {
            string longDateWithoutDayOfWeek = null;
            foreach (var pattern in cultureInfo.DateTimeFormat.GetAllDateTimePatterns('D'))
            {
                if (!pattern.Contains("ddd"))
                {
                    longDateWithoutDayOfWeek = pattern;
                    break;
                }
            }

            bool isFallbackRequired = string.IsNullOrEmpty(longDateWithoutDayOfWeek);
            if (isFallbackRequired)
            {
                longDateWithoutDayOfWeek = cultureInfo.DateTimeFormat.ShortDatePattern;
            }
            System.Console.WriteLine("{0} - {1} {2}", cultureInfo.Name, longDateWithoutDayOfWeek, (isFallbackRequired) ? " (short)" : string.Empty);
        }
    }

Alternatively, you can use the Windows.Globalization.DateTimeFormatting.DateTimeFormatter with template of "day month year" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM