Paul
Paul

Reputation: 620

Formatting dateTime with suffix

i have the following code and using a static method i am trying to add a suffix to the date time object and based on the outputFormat that is also passed im trying to format the date and return as as a string

var outputFormat = date.Month != nextDate.Month || isLast ?  "d MMMM yyyy" : "dd";

if (isLastMonthDay)
{
    formattedDate.AppendFormat("{0}{1}", GetDateSuffix(date, outputFormat), "<br><br>");
}
else
{
    formattedDate.AppendFormat("{0}{1}", GetDateSuffix(date, outputFormat).TrimStart('0'), ", ");
}

private static string GetDateSuffix(DateTime date, string outputFormat)
{
    string suffix;

    switch (date.Day)
    {
        case 1:
        case 21:
        case 31:
            suffix = "st";
            break;
        case 2:
        case 22:
           suffix = "nd";
            break;
        case 3:
        case 23:
            suffix = "rd";
            break;
        default:
            suffix = "th";
            break;
    }

    return outputFormat == "d MMMM yyyy" ? string.Format("{0}{1} {2:MMMM} {3}", date.Day, suffix, date.Month, date.Year) : string.Format("{0}{1}", date.Day, suffix);

}

I am getting the folowing result, i want the date to be output 4th April 2015 if teh outputFormat is specified as dd MMMM yyyy but i am getting MMMM returned. I have read http://www.csharp-examples.net/string-format-datetime/ and it says to use

String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month 

Can anyone see what im doing wrong please?

Thanks

enter image description here

Upvotes: 0

Views: 1548

Answers (1)

itsme86
itsme86

Reputation: 19526

Your problem is that you're passing date.Month (an int) instead of date (a DateTime) when formatting the string:

string.Format("{0}{1} {2:MMMM} {3}", date.Day, suffix, date.Month, date.Year)

This makes sense:

date.ToString("MMMM");

This does not:

date.Month.ToString("MMMM");

You should be able to just drop the .Month off of the argument you're passing in to fix your problem:

string.Format("{0}{1} {2:MMMM} {3}", date.Day, suffix, date, date.Year)

Upvotes: 1

Related Questions