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

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

    There is nothing in JDK to do this.

      static String[] suffixes =
      //    0     1     2     3     4     5     6     7     8     9
         { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
      //    10    11    12    13    14    15    16    17    18    19
           "th", "th", "th", "th", "th", "th", "th", "th", "th", "th",
      //    20    21    22    23    24    25    26    27    28    29
           "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
      //    30    31
           "th", "st" };
    
     Date date = new Date();
     SimpleDateFormat formatDayOfMonth  = new SimpleDateFormat("d");
     int day = Integer.parseInt(formatDateOfMonth.format(date));
     String dayStr = day + suffixes[day];
    

    Or using Calendar:

     Calendar c = Calendar.getInstance();
     c.setTime(date);
     int day = c.get(Calendar.DAY_OF_MONTH);
     String dayStr = day + suffixes[day];
    

    Per comments by @thorbjørn-ravn-andersen, a table like this can be helpful when localizing:

      static String[] suffixes =
         {  "0th",  "1st",  "2nd",  "3rd",  "4th",  "5th",  "6th",  "7th",  "8th",  "9th",
           "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th",
           "20th", "21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th",
           "30th", "31st" };
    

提交回复
热议问题