What is date format for 07th November 2021?
The tricky part is the "th", becasue it has to mutate to "st"/"nd"/"rd" for the some days of a month.
So these days require special-casing of this ordinal suffix, e.g:
string ordinalSuffix;
if (date.Day == 1 || date.Day == 21 || date.Day == 31)
ordinalSuffix = "st";
else if (date.Day == 2 || date.Day == 22)
ordinalSuffix = "nd";
else if (date.Day == 3 || date.Day == 23)
ordinalSuffix = "rd";
else
ordinalSuffix= "th";
string formatted = date.ToString($"dd'{ordinalSuffix}' MMMM yyyy");
You surely are aware that this works for English only. To support other languages, you might consider using a library like Humanizer.
Try to use this function here:
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);
}
You can call it like so:
DateTime(2021, 2, 21);
Console.WriteLine(dt.ToStringWithSuffix("dd'[$suffix]' MMMM yyyy"));
You can also check the documentation on Custom date and time format strings if you need other formats.
Source: https://gist.github.com/woodss/006f28f01dcf371c2bd1