Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I provide a suffix for days of the month?

Tags:

c

date

I need a function to return a suffix for days when displaying text like the "th" in "Wednesday June 5th, 2008".

It only need work for the numbers 1 through 31 (no error checking required) and English.

like image 439
paxdiablo Avatar asked Dec 02 '22 09:12

paxdiablo


2 Answers

Here is an alternative which should work for larger numbers too:

static const char *daySuffixLookup[] = { "th","st","nd","rd","th",
                           "th","th","th","th","th" };

const char *daySuffix(int n)
{
    if(n % 100 >= 11 && n % 100 <= 13)
        return "th";

    return daySuffixLookup[n % 10];
}
like image 53
Adam Pierce Avatar answered Dec 15 '22 23:12

Adam Pierce


The following function works for C:

char *makeDaySuffix (unsigned int day) {
    //if ((day < 1) || (day > 31)) return "";
    switch (day) {
        case 1: case 21: case 31: return "st";
        case 2: case 22:          return "nd";
        case 3: case 23:          return "rd";
    }
    return "th";
}

As requested, it only works for the numbers 1 through 31 inclusive. If you want (possibly, but not necessarily) raw speed, you could try:

char *makeDaySuffix (unsigned int day) {
    static const char * const suffix[] = {
        "st","nd","rd","th","th","th","th","th","th","th",
        "th","th","th","th","th","th","th","th","th","th"
        "st","nd","rd","th","th","th","th","th","th","th"
        "st"
    };
    //if ((day < 1) || (day > 31)) return "";
    return suffix[day-1];
}

You'll note that I have bounds checking in there though commented out. If there's even the slightest possibility that an unexpected value will be passed in, you'll probably want to uncomment those lines.

Just keep in mind that, with the compilers of today, naive assumptions about what is faster in a high-level language may not be correct: measure, don't guess.

like image 25
paxdiablo Avatar answered Dec 15 '22 23:12

paxdiablo