Created
December 4, 2014 12:21
-
-
Save woodss/006f28f01dcf371c2bd1 to your computer and use it in GitHub Desktop.
Including a Day Suffix when formatting a Date in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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