无法将整数月份转换为月份名称 android java

Can't convert int month to month name android java

我正在尝试将整数月份转换为月份名称(字符串)。我使用的是简单的日期格式,但所有月份都只得到 "Jan"。为什么会这样?

 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);

SimpleDateFormat#format() 方法有一个带有 Object 的重载,这就是为什么您可以将 int 传递给它的原因。但是,这不是您想要的方法。您想要一个带有 Date 对象的对象,我们可以从 Calendar 中获取并设置适当的月份:

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

在这种情况下传递 Locale.getDefault() 是多余的,因为如果没有另外指定,SimpleDateFormat 将使用它。

I get only "Jan" for all months

因为这里的String sdf = new SimpleDateFormat("LLL", Locale.getDefault()).format(monthOfYear);monthOfYear是Number Object所以,DateFormate class会把它从那个数转换成Date对象,就是在 1 Jan, 197012 Jan, 1970 之间,所以你整个月总是得到 Jan。

试试,

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 代码片段:

     /**
     * 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());
    }

tl;博士

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

java.time.Month

现在在 java.time 类 中更容易做到,取代了这些麻烦的旧遗留日期时间 类。

Month 枚举定义了十几个对象,每个月一个。

一月到十二月的月份编号为 1-12。

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

让对象生成一个 name of the month, automatically localized. Adjust the TextStyle to specify how long or abbreviated you want the name. Specify a Locale 的字符串来说明在翻译中应该使用哪种人类语言以及应该用什么文化规范来决定诸如缩写、标点符号和大写等问题。

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

关于java.time

java.time 框架内置于 Java 8 及更高版本中。这些 类 取代了麻烦的旧日期时间 类,例如 java.util.Date.Calendarjava.text.SimpleDateFormat

Joda-Time project, now in maintenance mode,建议迁移到java.time。

要了解更多信息,请参阅 Oracle Tutorial。并在 Stack Overflow 中搜索许多示例和解释。

许多 java.time 功能被反向移植到 ThreeTen-Backport and further adapted to Android in ThreeTenABP (see 中的 Java 6 & 7)。

ThreeTen-Extra 项目扩展了 java.time 并增加了 类。该项目是未来可能添加到 java.time 的试验场。您可能会在这里找到一些有用的 类,例如 IntervalYearWeekYearQuarter 等。