2

How to get the Android date format "7/25/2021" to July/25/2021

Here is the portion of the code

mDisplayDate is the Textview

mDisplayDate.setOnClickListener(view -> { Calendar cal = Calendar.getInstance();

        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

String dateLong = month + "/" + day+ "/" + year;

mDisplayDate.setText(dateLong);

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
speedflow
  • 75
  • 6
  • I hope this documentation page may help: https://developer.android.com/reference/java/text/SimpleDateFormat – Adarsh Anurag Jul 25 '21 at 12:20
  • @AdarshAnurag Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. We have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. – Ole V.V. Aug 01 '21 at 10:12
  • `LocalDate.parse("7/25/2021", DateTimeFormatter.ofPattern("M/d/u")).format(DateTimeFormatter.ofPattern("MMMM/d/u", Locale.ENGLISH))` yields `July/25/2021`. – Ole V.V. Aug 01 '21 at 10:14

2 Answers2

0

The easiest way to do this is to use a switch case

String monthStr = "";

switch(month) {
    case 1:
        monthStr = "January";
        break;
    case 2:
        monthStr = "February";
        break;
   // and else
}

String dateLong = monthStr + "/" + day+ "/" + year;
Pouria Hemi
  • 706
  • 5
  • 15
  • 30
0

You could use the android documentation link, that I shared in the comments to learn about SimpleDateFormat.

The Pattern to be used should be MMMM/dd/yyyy

  • MMMM - gives month name

  • dd - gives the days of the month

  • yyyy - gives the year

     Date date = Calendar.getInstance().getTime();
     DateFormat formatter = new SimpleDateFormat("MMMM/dd/yyyy");
     String today = formatter.format(date);
     mDisplayDate.setText(today);
    

Note: You may use MMM for month names in 3 letters only.

Read more about patterns here.

Adarsh Anurag
  • 630
  • 5
  • 17