How do you format the day of the month to say “11th”, “21st” or “23rd” (ordinal indicator)?

后端 未结 20 967
逝去的感伤
逝去的感伤 2020-11-22 02:41

I know this will give me the day of the month as a number (11, 21, 23):

SimpleDateFormat formatDayOfMonth = new Simple         


        
20条回答
  •  梦如初夏
    2020-11-22 02:50

    Only issue with the solution provided by Greg is that it does not account for number greater than 100 with the "teen" numbers ending. For example, 111 should be 111th, not 111st. This is my solution:

    /**
     * Return ordinal suffix (e.g. 'st', 'nd', 'rd', or 'th') for a given number
     * 
     * @param value
     *           a number
     * @return Ordinal suffix for the given number
     */
    public static String getOrdinalSuffix( int value )
    {
        int hunRem = value % 100;
        int tenRem = value % 10;
    
        if ( hunRem - tenRem == 10 )
        {
            return "th";
        }
        switch ( tenRem )
        {
        case 1:
            return "st";
        case 2:
            return "nd";
        case 3:
            return "rd";
        default:
            return "th";
        }
    }
    

提交回复
热议问题