With a DateTime
object, it's easy to get, for example, 11 October 2011 by using:
d.ToString("d MMMM yyyy");
However, there seems to be no built-in method to get the output 11th October 2011.
So here's a possible extension method.
public string ToStringWithOrdinal(this DateTime d) {
var sb = new StringBuilder(d.Day);
switch (d.Day) {
case 1:
case 21:
case 31:
sb.Append("st");
break;
case 2:
case 22:
sb.Append("nd");
break;
case 3:
case 23:
sb.Append("rd");
break;
default:
sb.Append("th");
break;
}
sb.Append(" ").Append(d.ToString("MMMM yyyy"));
return sb.ToString();
}
Can anyone think of any improvements, either to performance or to add functionality for a format
parameter, so we can call e.g. d.ToStringWithOrdinal("d^ MMMM");
?
Thanks.
str = day; str += "st"; ...
butreturn day + "st " + ...
. \$\endgroup\$