Is there a simple method of displaying the day portion of a date in the format 1st, 2nd, 3rd,…? I suspect that there is no method of doing this through custom datetime formatstrings (I will be very happy to be wrong), so has anyone implemented a way of doing this?
Asked
Active
Viewed 1,176 times
5
-
What language and .net version are you using ? – Vishal Mar 08 '11 at 17:45
-
Related: http://stackoverflow.com/questions/20156/is-there-an-easy-way-to-create-ordinals-in-c – StriplingWarrior Mar 08 '11 at 17:49
-
@Misnomer - using .Net 3.5 at the moment. I'll take answers in any .Net language. – detaylor Mar 08 '11 at 17:53
-
@StriplingWarrior - thanks for the link. I'll take a look and see if I implement a similar solution. – detaylor Mar 08 '11 at 17:53
2 Answers
9
This is the core logic for achieving this end:
string SuffixForDay(DateTime date) {
switch (date.Day) {
case 1:
case 21:
case 31:
return "st";
case 2:
case 22:
return "nd";
case 3:
case 23:
return "rd";
default:
return "th";
}
}

jason
- 236,483
- 35
- 423
- 525
-
+1 - For simple code..(and for previous comment on my deleted answer !) – Vishal Mar 08 '11 at 18:10
0
You can use the DateTime.Day property for this purpose.

Mikhail
- 9,186
- 4
- 33
- 49
-
...and write code to add the suffix dynamically: st, nd, rd, th (it seems there are only 4 cases) – Cosmin Mar 08 '11 at 17:50
-
Day would just return the integer value not the suffix "st", "rd", "th" etc – detaylor Mar 08 '11 at 17:51