Java如何获取当前月份的名称?

要从系统获取当前月份的名称,我们可以使用java.util.Calendarclass。Calendar.get(Calendar.MONTH)从0开始的第一个月和11作为上月的整数返回月份的值。这意味着一月等于0,二月等于1,十二月等于11。

让我们看下面的代码:

package org.nhooo.example.util;

import java.util.Calendar;

public class GetMonthNameExample {
    public static void main(String[] args) {
        String[] monthName = {"January", "February",
                "March", "April", "May", "June", "July",
                "August", "September", "October", "November",
                "December"};

        Calendar cal = Calendar.getInstance();
        String month = monthName[cal.get(Calendar.MONTH)];

        System.out.println("Month name: " + month);
    }
}

在main方法的第一行,我们声明一个字符串数组,其中保留了我们的月份名称。接下来,我们获得当前月份的整数值,并在最后一步中,在先前定义的数组中查找月份名称。

该程序的示例结果为:

Month name: January

获取月份名称或星期名称的更好方法是使用java.text.DateFormatSymbols该类。可在以下链接中找到有关使用此类的示例:如何获得月份名称列表?以及如何获取工作日名称列表?。