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

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

    Try below function:

    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);
    }
    

提交回复
热议问题