-1

I want to convert my date object in java to string of above format.

please note that it should have "st" or "nd" or "rd" or "th" in date

1 Answers1

0

Its not a good solution but I got the expected result with below way:

public static void main(String[] args) {
        MainClass mainClass = new MainClass();
        Date date = new Date();
        System.out.println(mainClass.getFormattedDate(date));
    }

    public String getFormattedDate(Date date){
         SimpleDateFormat formatDayOfMonth  = new SimpleDateFormat("d");
         int day = Integer.parseInt(formatDayOfMonth.format(date));

         SimpleDateFormat dateStr = new SimpleDateFormat("d'st' 'of' MMMM yyyy");

         String dayStr = dateStr.format(date).replace("st", getSuffixes(day));
         return dayStr;
    }

    private String getSuffixes(int day) {
        switch(day%10) {
            case 1: return "st";
            case 2: return "nd";
            case 3: return "rd";
            default: return "th";
        }
    }
Amit
  • 1,540
  • 1
  • 15
  • 28