Подтвердить что ты не робот

Название месяца как строка

Я пытаюсь вернуть имя месяца как String, например "May", "September", "November".

Я пробовал:

int month = c.get(Calendar.MONTH);

Однако это возвращает целые числа (5, 9, 11, соответственно). Как получить имя месяца?

4b9b3361

Ответ 1

Используйте getDisplayName.

Для более раннего использования API String.format(Locale.US,"%tB",c);

Ответ 2

Используйте это:

Calendar cal=Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMMM");
String month_name = month_date.format(cal.getTime());

Название месяца будет содержать полное название месяца, если вы хотите использовать короткое имя месяца это

 SimpleDateFormat month_date = new SimpleDateFormat("MMM");
 String month_name = month_date.format(cal.getTime());

Ответ 3

Для получения месяца в строковой переменной используйте код ниже

Например, сентябрь месяца:

M → 9

MM → 09

MMM → Сен

MMMM → Сентябрь

String monthname=(String)android.text.format.DateFormat.format("MMMM", new Date())

Ответ 4

SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );

Для некоторых языков (например, русский) это единственный правильный способ получить автономные месячные имена.

Это то, что вы получаете, если вы используете getDisplayName из Calendar или DateFormatSymbols для января:

января (что верно для полной строки даты: " 10 января, 2014" )

но в случае автономного имени месяца вы ожидаете:

январь

Ответ 5

Проще, чем этот

mCalendar = Calendar.getInstance();    
String month = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());

Ответ 6

Я сохраняю этот ответ, который полезен для других случаев, но ответ @trutheality кажется самым простым и прямым способом.

Вы можете использовать DateFormatSymbols

DateFormatSymbols(Locale.FRENCH).getMonths()[month]; // FRENCH as an example

Ответ 7

Отправляйтесь в проблемы API, поэтому я просто сделал свой собственный:

public static String getDate(){
    Time today = new Time(Time.getCurrentTimezone());
    today.setToNow();
    System.out.println(today.month);
    return today.monthDay+", "+ getMonthName(today.month)  +" "+today.year; 
}

public static String getMonthName(int month){
    switch(month+1){
    case 1:
        return "Jan";

    case 2:
        return "Feb";

    case 3:
        return "Mar";

    case 4:
        return "Apr";

    case 5:
        return "May";

    case 6:
        return "Jun";

    case 7:
        return "Jul";

    case 8:
        return "Aug";

    case 9:
        return "Sep";

    case 10:
        return "Oct";

    case 11:
        return "Nov";

    case 12:
        return "Dec";
    }

    return "";
}

Ответ 8

Единственный способ на Android, чтобы получить правильно отформатированное имя месяца stanalone для таких языков, как ukrainian, russian, czech

private String getMonthName(Calendar calendar, boolean short) {
    int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY | DateUtils.FORMAT_NO_YEAR;
    if (short) {
        flags |= DateUtils.FORMAT_ABBREV_MONTH;
    }
    return DateUtils.formatDateTime(getContext(), calendar.getTimeInMillis(), flags);
}

Протестировано по API 15-25

Выход для Май - Май, но не Мая

Ответ 9

Я бы рекомендовал использовать объект Calendar и Locale, так как имена месяцев для разных языков разные:

// index can be 0 - 11
private String getMonthName(final int index, final Locale locale, final boolean shortName)
{
    String format = "%tB";

    if (shortName)
        format = "%tb";

    Calendar calendar = Calendar.getInstance(locale);
    calendar.set(Calendar.MONTH, index);
    calendar.set(Calendar.DAY_OF_MONTH, 1);

    return String.format(locale, format, calendar);
}

Пример для полного имени месяца:

System.out.println(getMonthName(0, Locale.US, false));

Результат: January

Пример для короткого имени месяца:

System.out.println(getMonthName(0, Locale.US, true));

Результат: Jan

Ответ 10

Получение автономного имени месяца на удивление сложно выполнить "право" на Java. (По крайней мере, на момент написания этой статьи. В настоящее время я использую Java 8).

Проблема заключается в том, что на некоторых языках, включая русский и чешский, автономная версия месяца отличается от версии "форматирования". Кроме того, похоже, что ни один Java API просто не даст вам "лучшую" строку. Большинство ответов, размещенных здесь, пока только предлагают версию форматирования. Вставка ниже - это рабочее решение для получения автономной версии одного месяца или получение массива со всеми из них.

Надеюсь, это поможет кому-то еще некоторое время!

/**
 * getStandaloneMonthName, This returns a standalone month name for the specified month, in the
 * specified locale. In some languages, including Russian and Czech, the standalone version of
 * the month name is different from the version of the month name you would use as part of a
 * full date. (Different from the formatting version).
 *
 * This tries to get the standalone version first. If no mapping is found for a standalone
 * version (Presumably because the supplied language has no standalone version), then this will
 * return the formatting version of the month name.
 */
private static String getStandaloneMonthName(Month month, Locale locale, boolean capitalize) {
    // Attempt to get the standalone version of the month name.
    String monthName = month.getDisplayName(TextStyle.FULL_STANDALONE, locale);
    String monthNumber = "" + month.getValue();
    // If no mapping was found, then get the formatting version of the month name.
    if (monthName.equals(monthNumber)) {
        DateFormatSymbols dateSymbols = DateFormatSymbols.getInstance(locale);
        monthName = dateSymbols.getMonths()[month.getValue()];
    }
    // If needed, capitalize the month name.
    if ((capitalize) && (monthName != null) && (monthName.length() > 0)) {
        monthName = monthName.substring(0, 1).toUpperCase(locale) + monthName.substring(1);
    }
    return monthName;
}

/**
 * getStandaloneMonthNames, This returns an array with the standalone version of the full month
 * names.
 */
private static String[] getStandaloneMonthNames(Locale locale, boolean capitalize) {
    Month[] monthEnums = Month.values();
    ArrayList<String> monthNamesArrayList = new ArrayList<>();
    for (Month monthEnum : monthEnums) {
        monthNamesArrayList.add(getStandaloneMonthName(monthEnum, locale, capitalize));
    }
    // Convert the arraylist to a string array, and return the array.
    String[] monthNames = monthNamesArrayList.toArray(new String[]{});
    return monthNames;
}