2

I am trying to convert my month into the MMM format using SimpleDateFormat but i am unable to convert it.

    tvDisplayDate = (TextView) findViewById(R.id.dateDisplay);

    Calendar cal=Calendar.getInstance();

    SimpleDateFormat format = new SimpleDateFormat("MMM");

    int tempyear = cal.get(Calendar.YEAR);
    int tempmonth = cal.get(Calendar.MONTH);
    int tempday = cal.get(Calendar.DAY_OF_MONTH);

    String month = new Integer(tempmonth).toString();
dythe
  • 840
  • 5
  • 21
  • 45

3 Answers3

4

The following works (I just tested it)

Calendar cal=Calendar.getInstance();
int tempmonth = cal.get(Calendar.MONTH);

SimpleDateFormat newformat = new SimpleDateFormat("MMM");
SimpleDateFormat oldformat = new SimpleDateFormat("MM");

        String monthName = null;
        Date myDate;
        try {
            myDate = oldformat.parse(String.valueOf(tempmonth));
            monthName = newformat.format(myDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Log.d("MMM", monthName);
Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
0

You are not actually using the format you created. Try:

String month = format.format(tempmonth);

You can format the whole date at once with:

String dateString = sdf.format(cal.getTime());
Andy Harris
  • 928
  • 5
  • 10
0

I'd say use Joda Time, would make such things easier.

Anyway, this question here has several answers.

Community
  • 1
  • 1
Alabhya
  • 490
  • 1
  • 9
  • 16