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

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

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

Note. I do not want to use a custom format (d MMMM yyyy), since I want to keep the regional order settings.

+2
source share
5 answers

If you use one of the standard formats, then everything that is displayed will depend on the culture - so even if you can find something that does not display the day of the 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 one "d" from this format string. That would be pretty unpleasant though.

+4
source

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", "")); 
+5
source

try the following:

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

He will return you what you need!

+4
source

You must use "d" instead of "D" to get the desired result.

+3
source

Many cultures have several long date templates, and you can choose the first one that does not have a daily week template:

  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 Windows.Globalization.DateTimeFormatting.DateTimeFormatter with the template "day month year" .

+2
source

Source: https://habr.com/ru/post/954532/


All Articles