[ACCEPTED]-How to get a Long Date format from DateTime without a weekday-datetime-format

Accepted answer
Score: 12
String formattedDate = DateTime.Now.Date.ToLongDateString().Replace(DateTime.Now.DayOfWeek.ToString()+ ", ", "")

0

Score: 11

This seemed to do the trick.

  1. Enumerate all valid datetime patterns: CultureInfo.DateTimeFormat.GetAllDateTimePatterns
  2. Select longest pattern (presumably this is the best match) that:
    • Is a substring of the CultureInfo.DateTimeFormat.LongDatePattern
    • Does not contain "ddd" (short day name)
    • Does not contain "dddd" (long day name)

This appears 7 to come up with the strings I was looking 6 for.

See code below:

class DateTest
{
    static private string GetDatePatternWithoutWeekday(CultureInfo cultureInfo)
    {
        string[] patterns = cultureInfo e.DateTimeFormat.GetAllDateTimePatterns();

        string longPattern = cultureInfo.DateTimeFormat.LongDatePattern;

        string acceptablePattern = String.Empty;

        foreach (string pattern in patterns)
        {
            if (longPattern.Contains(pattern) && !pattern.Contains("ddd") && !pattern.Contains("dddd"))
            {
                if (pattern.Length > acceptablePattern.Length)
                {
                    acceptablePattern = pattern;
                }
            }
        }

        if (String.IsNullOrEmpty(acceptablePattern))
        {
            return longPattern;
        }
        return acceptablePattern;
    }

    static private void Test(string locale)
    {
        DateTime dateTime = new DateTime(2009, 12, 5);

        Thread.CurrentThread.CurrentCulture  = new CultureInfo(locale);

        string format = GetDatePatternWithoutWeekday(Thread.CurrentThread.CurrentCulture);

        string result = dateTime.ToString(format);

        MessageBox.Show(result);            
    }
}

Technically, it probably 5 wouldn't work if a long format had the name 4 of the day sandwiched in the middle. For 3 that, I should choose the pattern with longest 2 common substring instead of longest exact 1 match.

Score: 5

Improving on the accepted answer, GetAllDateTimePatterns can take 9 a parameter to restrict the result to patterns 8 relating to a standard format string, such 7 as 'D' for the long date pattern.

For example, GetAllDateTimePatterns('D') is 6 currently returning this for en-US:

"dddd, MMMM d, yyyy", "MMMM d, yyyy", "dddd, d MMMM, yyyy", "d MMMM, yyyy" 

and this 5 for zh-HK:

"yyyy'年'M'月'd'日'", "yyyy'年'MM'月'dd'日'", "yyyy年MMMd日", "yyyy年MMMd日, dddd"

Assuming they're listed in some 4 order of preference or prevalence, we can 3 select the first option that does not contain 2 the day of the week.

Here are extension methods 1 so you can simply use myDateTime.ToLongDateStringWithoutDayOfWeek() and myDateTime.ToLongDateTimeStringWithoutDayOfWeek().

public static string ToLongDateStringWithoutDayOfWeek(this DateTime d)
{
    return d.ToString(
               CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns('D')
                   .FirstOrDefault(a => !a.Contains("ddd") && !a.Contains("dddd")) 
               ?? "D");
}

public static string ToLongDateTimeStringWithoutDayOfWeek(this DateTime d, bool includeSeconds = false)
{
    char format = includeSeconds ? 'F' : 'f';
    return d.ToString(
               CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(format)
                   .FirstOrDefault(a => !a.Contains("ddd") && !a.Contains("dddd")) 
               ?? format.ToString()); 
}
Score: 4

A very awful, horrible way to accomplish 2 this is to remove the format specifiers 1 you don't want from the existing LongDatePattern:

public static string CorrectedLongDatePattern(CultureInfo cultureInfo)
{
    var info = cultureInfo.DateTimeFormat;

    // This is bad, mmmkay?
    return Regex.Replace(info.LongDatePattern, "dddd,?",String.Empty).Trim();
}
Score: 4

This is an improved answer from Reza, which 1 does not work correctly with some localizations.

string formattedDate = DateTime.Now.ToLongDateString()
   .Replace(DateTimeFormatInfo.CurrentInfo.GetDayName(DateTime.Now.DayOfWeek), "")
   .TrimStart(", ".ToCharArray());
Score: 2

If the LongDate sequence is also culture 10 specific, then I'm afraid you're out of 9 luck and you'll have to write actual code 8 for this. Otherwise, a collection of formatting tags will 7 do the trick.

I'm afraid what you'll have 6 to do is create an array of 7 strings (one 5 for each day) in the local culture, and 4 remove those strings from your LongDate 3 format output. Then make sure you remove 2 all duplicated /'s -'s and spaces.

Hope there's 1 a better way but I don't see it.

Score: 2

This is an old, old thead, but I came across 8 it because it perfectly matched the use 7 case I needed to solve. I ended up writing 6 a piece of code that works, so I thought 5 I'd include it for those that need it. (It 4 has a few extra tricks, like defaulting 3 to the current date, and allowing either 2 the full date string for a culture, or one 1 with the day-of-the-week removed):

 public string DateString(DateTime? pDt = null, string lang, bool includeDayOfWeek = true)
 {
    if (pDt == null) pDt = DateTime.Now;
    DateTime dt = (DateTime)pDt;

    System.Globalization.CultureInfo culture = null; 
    try {   culture = new System.Globalization.CultureInfo(lang); } 
       catch{ culture = System.Globalization.CultureInfo.InvariantCulture; }

    string ss = dt.ToString("D", culture);
    if (!includeDayOfWeek)
    {
       //  Find day-of-week string, and remove it from the date string
       //  (including any trailing spaces or punctuation)
       string dow = dt.ToString("dddd", culture);
       int len = dow.Length;
       int pos = ss.IndexOf(dow);
       if (pos >= 0)
       {
          while ( ((len + pos) < ss.Length)  &&  ( !Char.IsLetterOrDigit(ss[len+pos])))
             len++;
          ss = ss.Substring(0, pos) + ss.Substring(len+pos, ss.Length - (len+pos));
       }
    }
   return ss;
 }
Score: 1

I have expanded on the suggestion by Bart 14 Calixto to fix the dd MMM yyyy format issue 13 (here in Australia we also use UK date 12 format dd/mm/yy)

I also frequently need to 11 convert between Aust and US date formats.

This 10 code fixes the problem (my version is in 9 VB)

Public Shared Function ToLongDateWithoutWeekDayString(source As DateTime, cult As System.Globalization.CultureInfo) As String

Return source.ToString("D", cult).Replace(source.DayOfWeek.ToString(), "").Trim(","c, " "c)

End Function

Before calling the function you need 8 to set culture, I do it this way after getting 7 the visitor's country from http://ipinfo.io

Select Case Country.country
            Case "AU"
                cult = New CultureInfo("en-AU")
            Case "US"
                cult = New CultureInfo("en-US")
            Case "GB"
                cult = New CultureInfo("en-GB")
        End Select

Dim date1 As New Date(2010, 8, 18)
lblDate.Text = ToLongDateWithoutWeekDayString(date1, cult)

After setting 6 AU or GB culture result is 18 August 2010

After 5 setting US culture result is August 18, 2010

Adam 4 do you agree this solves the formatting 3 issue you refer to?

Thanks Bart that was 2 very nice code.

Dont forget to add Dim cult As System.Globalization.CultureInfo after Inherits 1 System.Web.UI.Page

Score: 0

Why not get the LongDate and trim off the 1 first portion where the weekday appears?

DateTime date = Convert.ToDateTime(content["DisplayDate"]); 
  //-->3/15/2016 2:09:13 PM

string newDate = date.ToString("D", new CultureInfo("es-ES")); 
  //--> martes, 15 de marzo de 2016

var index = newDate.IndexOf(",") + 1;
  //--> 7

string finalDate = newDate.Substring(index);
  //--> 15 de marzo de 2016
Score: 0

Old post, but I'm using this:

public static string ToLongDateWithoutWeekDayString(this DateTime source)
{
    return source.ToLongDateString()
                 .Replace(source.DayOfWeek.ToString(), "")
                 .Trim(',', ' ');
}

0

Score: 0

My solution:

DateTime date = DateTime.Now;
CultureInfo culture = CultureInfo.CurrentCulture;
string dayName = date.ToString("dddd", culture);
string fullDate = date.ToString("f", culture);
string trim = string.Join(" ", fullDate.Replace(dayName, "").TrimStart(',').TrimStart(' ').Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); 

The last line:

  1. Removes leftover comma at start
  2. Removes leftover space at start
  3. Removes leftover double-space from anywhere in the string

Tested for each 1 culture from

CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
Score: 0

You can concatenate the standard month/day 3 pattern (m) with custom year (yyyy):

string formattedDate = date.ToString("M") + ", " + date.ToString("yyyy");

Examples:

June 2 15, 2020 (en-US)
15. juni, 2020 (da-DK)
15 1 Juni, 2020 (id-ID)

Score: 0

Kinda hilarious how many answers this question 5 has (and that it's still an issue). Might 4 as well join the party with my solution:

    CultureInfo culture = CultureInfo.CurrentCulture; // or replace with the culture of your choosing

    string pattern = culture.DateTimeFormat.LongDatePattern
        .Replace("dddd, ", "")
        .Replace(",dddd", "");

    return dt.ToString(pattern, culture);

Then 3 you've got both cases covered whether the 2 day of the week precedes or follows the 1 rest.

More Related questions