Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a Date with "ShortenedMonth/dd" format

Is there a way I can get a date by the format "MM/dd" but instead of the month being an int, it is a shortened string like "Jan 30"?

Currently I did this with Java by a simple Switch Case, but I want to know if this is already contained in a DateFormat or something similar.

Anyway I leave here my current code. I used R.string because my application has multi-language support.

public void setShortMonth(){
   final Calendar calendar = Calendar.getInstance();
   int Month = calendar.get(Calendar.MONTH);
   String ShortMonth = " ";
   switch (Month){
        case 0: 
            ShortMonth = getString(R.string.Jan);
            break;
        case 1: 
            ShortMonth = getString(R.string.Fev);
            break;
        case 2: 
            ShortMonth = getString(R.string.Mar);
            break;
        case 3: 
            ShortMonth = getString(R.string.Apr);
            break;
        case 4: 
            ShortMonth = getString(R.string.May);
            break;
        case 5: 
            ShortMonth = getString(R.string.Jun);
            break;
        case 6: 
            ShortMonth = getString(R.string.Jul);
            break;
        case 7: 
            ShortMonth = getString(R.string.Aug);
            break;
        case 8: 
            ShortMonth = getString(R.string.Sep);
            break;
        case 9: 
            ShortMonth = getString(R.string.Oct);
            break;
        case 10: 
            ShortMonth = getString(R.string.Nov);
            break;
        case 11: 
            ShortMonth = getString(R.string.Dec);
            break;
        }
        TextView datetxt = (TextView) findViewById(R.id.home_date);
        datetxt.setText(ShortMonth + " " + Day);
}
like image 576
Sergio Carneiro Avatar asked Dec 16 '22 22:12

Sergio Carneiro


1 Answers

Try like this:

final Calendar calendar = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("MMM dd"); // 3-letter month name & 2-char day of month
TextView datetxt = (TextView) findViewById(R.id.home_date);
datetxt.setText(formatter.format(calendar.getTime()));

You can see a list of available format options here.

like image 112
Caner Avatar answered Dec 28 '22 04:12

Caner