UPDATE
NuGet Package:
https://www.nuget.org/packages/DateTimeToStringWithSuffix
Example:
https://dotnetfiddle.net/zXQX7y
Support:
.NET Core 1.0 and higher
.NET Framework 4.5 and higher
Here's an extension method (because everyone loves extension methods), with Lazlow's answer as the basis (chose Lazlow because it's easy to read).
It works the same as the regular ToString() method in DateTime except that if the format contains d or dd , the suffix will be added automatically.
/// <summary> /// Return a DateTime string with suffix eg "st", "nd", "rd", "th" /// So a format "dd-MMM-yyyy" could return "16th-Jan-2014" /// </summary> public static string ToStringWithSuffix(this DateTime dateTime, string format, string suffixPlaceHolder = "$") { if(format.LastIndexOf("d", StringComparison.Ordinal) == -1 || format.Count(x => x == 'd') > 2) { return dateTime.ToString(format); } string suffix; switch(dateTime.Day) { case 1: case 21: case 31: suffix = "st"; break; case 2: case 22: suffix = "nd"; break; case 3: case 23: suffix = "rd"; break; default: suffix = "th"; break; } var formatWithSuffix = format.Insert(format.LastIndexOf("d", StringComparison.InvariantCultureIgnoreCase) + 1, suffixPlaceHolder); var date = dateTime.ToString(formatWithSuffix); return date.Replace(suffixPlaceHolder, suffix); }
GFoley83 Feb 21 '14 at 6:12 2014-02-21 06:12
source share