UPDATE
NuGet package:
https://www.nuget.org/packages/DateTimeToStringWithSuffix
Example:
https://dotnetfiddle.net/zXQX7y
Supports:
.NET Core 1.0 and higher
.NET Framework 4.5 and high
Here's an extension method (because everyone loves extension methods), with Lazlow's answer as the basis (picked Lazlow's as it's easy to read).
Works just like the regular ToString()
method on DateTime
with the exception that if the format contains a d
or dd
, then the suffix will be added automatically.
/// <summary>
/// Return a DateTime string with suffix e.g. "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);
}