Skip to content

Instantly share code, notes, and snippets.

@woodss
Created December 4, 2014 12:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woodss/006f28f01dcf371c2bd1 to your computer and use it in GitHub Desktop.
Save woodss/006f28f01dcf371c2bd1 to your computer and use it in GitHub Desktop.
Including a Day Suffix when formatting a Date in C#
namespace System {
/// <summary>
? /// Convert a day of the month into one with a suffix attached
/// </summary>
/// <requires>
/// A string representing the correct suffix for a given day of the month
/// </requires>
public static string ToStringWithSuffix(this DateTime dt, string format) {
// The format parameter MUST contain [$suffix] within it, which will be replaced.
int day = dt.Day; string suffix = "";
// Exception for the 11th, 12th, & 13th
// (which would otherwise end up as 11st, 12nd, 13rd)
if (day % 100 >= 11 && day % 100 <= 13) {
suffix = "th";
}else{
switch (day % 10) {
case 1:
suffix = "st";
break;
case 2:
suffix = "nd";
break;
case 3:
suffix = "rd";
break;
default:
suffix = "th";
break;
}
}
// Convert the date to the format required, then add the suffix.
return dt.ToString(format).replace("[$suffix]",suffix);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment