Search code examples
javaandroiddatepickermonthcalendar

Month name from Month Numbers in android


I have a problem with converting the month number into month Name that is if month number 1 or 2 its returning March only. But for 1 it should return Feb right ? Previously i had this same problem for one day but next day it automatically worked i don;t How? But today again its showing like this I need some help to FIX it

public static String getMonthShortName(int monthNumber) {
    String monthName = "";

    if (monthNumber >= 0 && monthNumber < 12)
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.MONTH, monthNumber);

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM");
            //simpleDateFormat.setCalendar(calendar);
            monthName = simpleDateFormat.format(calendar.getTime());
        } catch (Exception e) {
            if (e != null)
                e.printStackTrace();
        }
    return monthName;
}

if monthNumber 1 or 2 in this statement

monthName = simpleDateFormat.format(calendar.getTime());

its returning Mar (March) only. But for the other numbers its working fine. Can any one of help me out of this ?


Solution

  • The issue appears because February has less than 30 days.

    For example, running this today (30.04.2014) :

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.MONTH, 1);
    System.out.println(calendar.getTime());
    

    returns

    Sun Mar 02 14:52:28 CET 2014
    

    You should add in your code before setting month :

    calendar.set(Calendar.DAY_OF_MONTH, 1);