13

I want to get the day in "6th 7th.. etc." of the Date string.

I have tried SimpleDateFormater & also try with DateFormatSymbols. I am not getting String Required.

Is there any Workaround?

Rahul Khurana
  • 8,577
  • 7
  • 33
  • 60
  • 2
    Create your own SimpleDateForter using Format() method – Lucifer Apr 25 '12 at 13:37
  • the `'st', 'nd', 'th'` part will be achieved with some logic because there isn't any date modifier which handles it automatically – waqaslam Apr 25 '12 at 13:47
  • try as answer given at http://stackoverflow.com/questions/4011075/how-do-you-format-the-day-of-the-month-to-say-11th-21st-or-23rd-in-java – Khan Apr 25 '12 at 13:59
  • Possible duplicate of [How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?](https://stackoverflow.com/questions/4011075/how-do-you-format-the-day-of-the-month-to-say-11th-21st-or-23rd-ordinal) – Ole V.V. Oct 01 '18 at 09:50

9 Answers9

26
SimpleDateFormat format = new SimpleDateFormat("d");
String date = format.format(new Date());

if(date.endsWith("1") && !date.endsWith("11"))
    format = new SimpleDateFormat("EE MMM d'st', yyyy");
else if(date.endsWith("2") && !date.endsWith("12"))
    format = new SimpleDateFormat("EE MMM d'nd', yyyy");
else if(date.endsWith("3") && !date.endsWith("13"))
    format = new SimpleDateFormat("EE MMM d'rd', yyyy");
else 
    format = new SimpleDateFormat("EE MMM d'th', yyyy");

String yourDate = format.format(new Date());

Try this, This looks like some static but works fine...

V.J.
  • 9,492
  • 4
  • 33
  • 49
8

Here you go:

/**
 * Converts Date object into string format as for e.g. <b>April 25th, 2012</b>
 * @param date date object
 * @return string format of provided date object
 */
public static String getCustomDateString(Date date){
    SimpleDateFormat tmp = new SimpleDateFormat("MMMM d");

    String str = tmp.format(date);
    str = str.substring(0, 1).toUpperCase() + str.substring(1);

    if(date.getDate()>10 && date.getDate()<14)
        str = str + "th, ";
    else{
        if(str.endsWith("1")) str = str + "st, ";
        else if(str.endsWith("2")) str = str + "nd, ";
        else if(str.endsWith("3")) str = str + "rd, ";
        else str = str + "th, ";
    }

    tmp = new SimpleDateFormat("yyyy");
    str = str + tmp.format(date);

    return str;
}

Sample:

Log.i("myDate", getCustomDateString(new Date()));

April 25th, 2012

waqaslam
  • 67,549
  • 16
  • 165
  • 178
1

You could subclass SimpleDateFormat and override format, and use a simple utility function that takes in a String or Integer and returns a String with either "nd" or "st" attached...something like:

if (initialDate.equals("2") || initialDate.equals("22"){
    return initialDate += "nd";
}else if {initialDate.equals("3") || initialDate.equals("23"){
    return initialDate += "rd";
}else{
    return initialDate += "th";
}
Sam Dozor
  • 40,335
  • 6
  • 42
  • 42
1

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:- September 1st, 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("MMMM d'st', yyyy").format(date);
        case 2:  
            return new SimpleDateFormat("MMMM d'nd', yyyy").format(date);
        case 3:  
            return new SimpleDateFormat("MMMM d'rd', yyyy").format(date);
        default: 
            return new SimpleDateFormat("MMMM d'th', yyyy").format(date);
    }
Nadeeshani
  • 493
  • 4
  • 8
1

For anyone that wants a clean static Kotlin version using SimpleDateFormat:

class Utils {

    companion object {
        private val dateFormat = SimpleDateFormat("MMM d, yyyy", Locale.getDefault())

       fun formatDate(date: Date): String {
            val oi = getOrdinalIndicator(date)
            return dateFormat.apply {
                applyPattern("MMM d'$oi', yyyy")
            }.format(date)
        }

        private fun getOrdinalIndicator(date: Date): String {
            val day = newCalendar(date).get(Calendar.DAY_OF_MONTH)

            if (day == 11 || day == 12 || day == 13) {
                return "th"
            }

            return when (day % 10) {
                1 -> "st"
                2 -> "nd"
                3 -> "rd"
                else -> "th"
            }
        }

        private fun newCalendar(date: Date): Calendar {
            return Calendar.getInstance().apply {
                time = date
            }
        }
    }
}
Anthony Cannon
  • 1,245
  • 9
  • 20
0

Below code can be useful ;

  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  Date date1 = format.parse("2018-06-06");
  String date = format.format(date1);

  if(date.endsWith("01") && !date.endsWith("11"))
    format = new SimpleDateFormat("d'st' MMM, yyyy");

  else if(date.endsWith("02") && !date.endsWith("12"))
    format = new SimpleDateFormat("d'nd' MMM, yyyy");

  else if(date.endsWith("03") && !date.endsWith("13"))
    format = new SimpleDateFormat("d'rd' MMM, yyyy");

  else
    format = new SimpleDateFormat("d'th' MMM, yyyy");

String yourDate = format.format(date1);

You'll get 6th Jun, 2018 .

Vishal Vaishnav
  • 3,346
  • 3
  • 26
  • 57
0
    public static String getDateText(String day){
      if(day.equalsIgnoreCase("1") || day.equalsIgnoreCase("21") || 
        day.equalsIgnoreCase("31")){
        return "st";
      }else if(day.equalsIgnoreCase("2") || day.equalsIgnoreCase("22")){
        return "nd";
      }else if(day.equalsIgnoreCase("3") || day.equalsIgnoreCase("23")){
        return "rd";
      }else {
        return "th";
      }
    }
shashank J
  • 67
  • 7
0

So here is the working code written in kotlin.

         /**
         * Format the given date like Today, Tomorrow, Yesterday, 11th Nov, 2nd Dec etc.
         */
        fun getFormattedDay(context: Context, strFromDate: String, strFromDateFormat: String) : String
        {
            var formattedDay = ""
            val fromDateFormatter = SimpleDateFormat(strFromDateFormat, Locale.UK)
            val fromDate = fromDateFormatter.parse(strFromDate)

            val tty = getTTYDay(context, strFromDate, strFromDateFormat)
            if (!tty.isEmpty()) {
                return tty
            }

            val dayFormatter = Constants.SIMPLE_DATE_FORMAT_D
            val monthAndYearFormatter = Constants.SIMPLE_DATE_FORMAT_MMM_YYYY

            formattedDay = dayFormatter.format(fromDate)
            val dayOfMonth = formattedDay.toInt()

            if (dayOfMonth in 11..13) {
                formattedDay += "th, "
            }
            else {
                if (formattedDay.endsWith("1")) {
                    formattedDay += "st, "
                }
                else if (formattedDay.endsWith("2")) {
                    formattedDay += "nd, "
                }
                else if (formattedDay.endsWith("3")) {
                    formattedDay += "rd, "
                }
                else {
                    formattedDay += "th, "
                }
            }

            formattedDay += monthAndYearFormatter.format(fromDate)

            return formattedDay
        }

        /**
         * This method returns today, tomorrow or yesterday or else empty string.
         */
        fun getTTYDay(context: Context, strFromDate: String, strFromDateFormat: String) : String
        {
            val fromDateFormatter = SimpleDateFormat(strFromDateFormat, Locale.UK)
            return if (strFromDate == fromDateFormatter.format(Date())) {
                context.getString(R.string.today)
            }
            else if (strFromDate == fromDateFormatter.format(getYesterdayDate())) {
                context.getString(R.string.yesterday)
            }
            else if (strFromDate == fromDateFormatter.format(getTomorrowDate())) {
                context.getString(R.string.tomorrow)
            }
            else {
                ""
            }
        }

        fun getYesterdayDate(): Date {
            val cal = Calendar.getInstance()
            cal.add(Calendar.DATE, -1)
            return cal.time
        }

        fun getTomorrowDate(): Date {
            val cal = Calendar.getInstance()
            cal.add(Calendar.DATE, 1)
            return cal.time
        }

This method can be invoked as static as well. How to use ?

Call this method like

getFormattedDay(context!!, "16/11/2018", "dd/MM/yyyy")

You will get the result like:

Today or Tomorrow or Yesterday or 16th, Nov 2018

Hope this helps you. If you do not want today, tomorrow then remove getTTYDay method calling.

Different types of date formats used:

        val DATE_FORMAT_DD_MM_YYYY_1 = "dd/MM/yyyy"
        val DATE_FORMAT_DD_MM_YYYY_2 = "dd MM yyyy"
        val DATE_FORMAT_DD_MMM_YYYY_1 = "dd MMM yyyy"
        val DATE_FORMAT_MMM_YYYY_1 = "MMM yyyy"
        val DATE_FORMAT_D_1 = "d"

        val SIMPLE_DATE_FORMAT_DD_MM_YYYY = SimpleDateFormat(DATE_FORMAT_DD_MM_YYYY_2, Locale.UK)
        val SIMPLE_DATE_FORMAT_DD_MMM_YYYY = SimpleDateFormat(DATE_FORMAT_DD_MMM_YYYY_1, Locale.UK)
        val SIMPLE_DATE_FORMAT_MMM_YYYY = SimpleDateFormat(DATE_FORMAT_MMM_YYYY_1, Locale.UK)
        val SIMPLE_DATE_FORMAT_D = SimpleDateFormat(DATE_FORMAT_D_1, Locale.UK)
Smeet
  • 4,036
  • 1
  • 36
  • 47
0

Kotlin version - updated code

     fun getFormattedDate(dateStr: String):String{
        try {
            var format = SimpleDateFormat("MM/dd/yyyy")//change your timeformat
            val date1 = format.parse(dateStr)
            var date = format.format(date1)

            if (date.startsWith("1") && !date.startsWith("11"))
                format = SimpleDateFormat("d'st' MMM, yyyy")
            else if (date.startsWith("2") && !date.startsWith("12"))
                format = SimpleDateFormat("d'nd' MMM, yyyy")
            else if (date.startsWith("3") && !date.startsWith("13"))
                format = SimpleDateFormat("d'rd' MMM, yyyy")
            else
                format = SimpleDateFormat("d'th' MMM, yyyy")

            val yourDate = format.format(date1)
            return yourDate
        }
        catch (ex: Exception){
            return dateStr
        }
    }
Ranjithkumar
  • 16,071
  • 12
  • 120
  • 159