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

后端 未结 20 885
逝去的感伤
逝去的感伤 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 03:08

    The following method can be used to get the formatted string of the date which is passed in to it. It'll format the date to say 1st,2nd,3rd,4th .. using SimpleDateFormat in Java. eg:- 1st of September 2015

    public String getFormattedDate(Date date){
                Calendar cal=Calendar.getInstance();
                cal.setTime(date);
                //2nd of march 2015
                int day=cal.get(Calendar.DATE);
    
                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);
            }
    

提交回复
热议问题