Getting day suffix when using DateTime.ToString()
Is it possible to include the day suffix when formatting a date using DateTime.ToString()?
For example I would like to print the date in the following format - Monday 27th July 2009. However the closest example I can find using DateTime.ToString() is Monday 27 July 2009.
Can I do this with DateTime.ToString() or am I going to have to fall back to my own code?
Solution 1:
Another option using switch:
string GetDaySuffix(int day)
{
switch (day)
{
case 1:
case 21:
case 31:
return "st";
case 2:
case 22:
return "nd";
case 3:
case 23:
return "rd";
default:
return "th";
}
}
Solution 2:
As a reference I always use/refer to [SteveX String Formatting] 1 and there doesn't appear to be any "th" in any of the available variables but you could easily build a string with
string.Format("{0:dddd dd}{1} {0:MMMM yyyy}", DateTime.Now, (?));
You would then have to supply a "st" for 1, "nd" for 2, "rd" for 3, and "th" for all others and could be in-lined with a "? :" statement.
var now = DateTime.Now;
(now.Day % 10 == 1 && now.Day % 100 != 11) ? "st"
: (now.Day % 10 == 2 && now.Day % 100 != 12) ? "nd"
: (now.Day % 10 == 3 && now.Day % 100 != 13) ? "rd"
: "th"