Search code examples
datetime.net-3.5ordinals

Formatting a DateTime value Day value


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?


Solution

  • 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";
         }
     }