Search code examples
jsfdatenumbersconvertersordinal

Adding day number ordinal suffixes like st, nd and th using f:convertDateTime


I would to add day number ordinal suffixs 26th, or 1st, or 2nd.

How can I do this in JSF using <f:convertDateTime>? I have tried using pattern attribute with dd, however this only prints the whole number without any ordinal suffix.


Solution

  • Unfortunately, this isn't supported by SimpleDateFormat which is being used under the covers by <f:convertDateTime>.

    You'd need to write a custom EL function for this. Such a function could look like this:

    public static String getDayWithSuffix(Date date) {
        if (date == null) {
            return null;
        }
    
        int day = Integer.valueOf(new SimpleDateFormat("d").format(date));
    
        if (day / 10 == 1) {
            return day + "th";
        }
    
        switch (day % 10) {
            case 1: return day + "st";
            case 2: return day + "nd";
            case 3: return day + "rd";
            default: return day + "th";
        }
    }
    

    And be used like this:

    #{my:getDayWithSuffix(bean.date)}
    

    For remainder, like month of year, just use another output with <f:convertDateTime> the usual way.