5
\$\begingroup\$

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.

\$\endgroup\$
  • 2
    \$\begingroup\$ Don't be lured by the false sense of security that using a string builder gives you here. It's only useful if you're really going to be adding a lot of different strings to it. Otherwise it just makes your code more complicated than it has to be. String concatenation really would be the best thing to use for your example in this case. (and by that, I mean, return the full concatenated result, not str = day; str += "st"; ... but return day + "st " + .... \$\endgroup\$ – Jeff Mercado Oct 11 '11 at 19:08
  • \$\begingroup\$ @Jeff Mercado +1, I've seen a lot of different suggestions but the general consensus is that it's only worth using a StringBuilder if you're doing 10+ concats.. \$\endgroup\$ – MattDavey Oct 14 '11 at 8:45
5
\$\begingroup\$

You can simplify it a bit and make a trivial improvement to performance (this will be noticeable if you call this method a lot).

public static string ToStringWithOrdinal(this DateTime d) {
  switch (d.Day) {
    case 1: case 21: case 31:
      return d.ToString("dd'st' MMMM yyyy");
    case 2: case 22:
      return d.ToString("dd'nd' MMMM yyyy");
    case 3: case 23:
      return d.ToString("dd'rd' MMMM yyyy");
    default:
      return d.ToString("dd'th' MMMM yyyy");
  }
}

As a side note this format doesn't read well to me. Normally I would write it as follows:

October 11th 2011

Is this format common in the UK?

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Yeah in the UK we normally put the day first. ;) Thanks for your amendment, that is better. \$\endgroup\$ – James Oct 11 '11 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.