0

I am trying to convert int month to month name(string). I am using simple date format but I get only "Jan" for all months. why is this happening?

 public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

        String sdf  = new SimpleDateFormat("LLL", Locale.getDefault()).format(monthOfYear);

    String date = +dayOfMonth+" "+(sdf);
    dateTextView.setText(date);
spykeburn
  • 153
  • 1
  • 19
  • 1
    Possible duplicate of [How can I convert an Integer to localized month name in Java?](http://stackoverflow.com/questions/1038570/how-can-i-convert-an-integer-to-localized-month-name-in-java) – Rahul Chaurasia Nov 18 '15 at 03:52

3 Answers3

4

I get only "Jan" for all months

Because String sdf = new SimpleDateFormat("LLL", Locale.getDefault()).format(monthOfYear); here, monthOfYear is Number Object so, DateFormate class will convert it to Date object from that number, which will be between 1 Jan, 1970 to 12 Jan, 1970 so you are always getting Jan for all month.

Try,

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, monthOfYear);
sdf  = new SimpleDateFormat("LLL", Locale.getDefault()).format(calendar.getTime());

 or

sdf = new DateFormatSymbols().getShortMonths()[monthOfYear];

DateFormat code snippet:

     /**
     * Formats the specified object as a string using the pattern of this date
     * format and appends the string to the specified string buffer.
     * <p>
     * If the {@code field} member of {@code field} contains a value specifying
     * a format field, then its {@code beginIndex} and {@code endIndex} members
     * will be updated with the position of the first occurrence of this field
     * in the formatted text.
     *
     * @param object
     *            the source object to format, must be a {@code Date} or a
     *            {@code Number}. If {@code object} is a number then a date is
     *            constructed using the {@code longValue()} of the number.
     * @param buffer
     *            the target string buffer to append the formatted date/time to.
     * @param field
     *            on input: an optional alignment field; on output: the offsets
     *            of the alignment field in the formatted text.
     * @return the string buffer.
     * @throws IllegalArgumentException
     *            if {@code object} is neither a {@code Date} nor a
     *            {@code Number} instance.
     */
    @Override
    public final StringBuffer format(Object object, StringBuffer buffer, FieldPosition field) {
        if (object instanceof Date) {
            return format((Date) object, buffer, field);
        }
        if (object instanceof Number) {
            return format(new Date(((Number) object).longValue()), buffer, field);
        }
        throw new IllegalArgumentException("Bad class: " + object.getClass());
    }
Dhaval Patel
  • 10,119
  • 5
  • 43
  • 46
2

The SimpleDateFormat#format() method has an overload that takes an Object, which is why you're able to pass an int to it. However, this is not the method you want. You want the one that takes a Date object, which we can get from a Calendar with the appropriate month set:

private String getMonthAbbr(int monthOfYear) {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.MONTH, monthOfYear);
    return new SimpleDateFormat("LLL").format(c.getTime()); 
}

Passing Locale.getDefault() is redundant in this case, as that is what SimpleDateFormat will use if it's not specified otherwise.

Mike M.
  • 38,532
  • 8
  • 99
  • 95
0

tl;dr

Month.of( yourMonthNumber ).getDisplayName( TextStyle.SHORT_STANDALONE , Locale.CANADA_FRENCH )

java.time.Month

Much easier to do now in the java.time classes that supplant these troublesome old legacy date-time classes.

The Month enum defines a dozen objects, one for each month.

The months are numbered 1-12 for January-December.

Month month = Month.of( 2 );  // 2 → February.

Ask the object to generate a String of the name of the month, automatically localized. Adjust the TextStyle to specify how long or abbreviated you want the name. Specify a Locale to say which human language should be used in translation and what cultural norms should decide issues such as abbreviation, punctuation, and capitalization.

String output = Month.FEBRUARY.getDisplayName( TextStyle.SHORT_STANDALONE , Locale.CANADA_FRENCH );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154