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

后端 未结 20 1002
逝去的感伤
逝去的感伤 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:57

    Question is little old. As this question is very noisy so posting what I did solved with static method as a util. Just copy, paste and use it!

     public static String getFormattedDate(Date date){
                Calendar cal=Calendar.getInstance();
                cal.setTime(date);
                //2nd of march 2015
                int day=cal.get(Calendar.DATE);
    
                if(!((day>10) && (day<19)))
                switch (day % 10) {
                case 1:  
                    return new SimpleDateFormat("d'st' 'of' MMMM yyyy").format(date);
                case 2:  
                    return new SimpleDateFormat("d'nd' 'of' MMMM yyyy").format(date);
                case 3:  
                    return new SimpleDateFormat("d'rd' 'of' MMMM yyyy").format(date);
                default: 
                    return new SimpleDateFormat("d'th' 'of' MMMM yyyy").format(date);
            }
            return new SimpleDateFormat("d'th' 'of' MMMM yyyy").format(date);
        }
    

    For testing purose

    Example: calling it from main method!

    Date date = new Date();
            Calendar cal=Calendar.getInstance();
            cal.setTime(date);
            for(int i=0;i<32;i++){
              System.out.println(getFormattedDate(cal.getTime()));
              cal.set(Calendar.DATE,(cal.getTime().getDate()+1));
            }
    

    Output:

    22nd of February 2018
    23rd of February 2018
    24th of February 2018
    25th of February 2018
    26th of February 2018
    27th of February 2018
    28th of February 2018
    1st of March 2018
    2nd of March 2018
    3rd of March 2018
    4th of March 2018
    5th of March 2018
    6th of March 2018
    7th of March 2018
    8th of March 2018
    9th of March 2018
    10th of March 2018
    11th of March 2018
    12th of March 2018
    13th of March 2018
    14th of March 2018
    15th of March 2018
    16th of March 2018
    17th of March 2018
    18th of March 2018
    19th of March 2018
    20th of March 2018
    21st of March 2018
    22nd of March 2018
    23rd of March 2018
    24th of March 2018
    25th of March 2018
    

提交回复
热议问题