HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMinor

Convert .NET DateTime to a string using ordinals

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertnetusingordinalsstringdatetime

Problem

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.

Solution

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?

Code Snippets

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");
  }
}

Context

StackExchange Code Review Q#5304, answer score: 5

Revisions (0)

No revisions yet.