如何在Java中将整数转换为本地化的月份名称?

如何在Java中将整数转换为本地化的月份名称?,java,date,locale,Java,Date,Locale,我得到一个整数,我需要转换为不同地区的月份名称: 美国语言环境示例: 1->1月 2月->2月 区域设置es mx示例: 1->Enero 2->Febrero我会使用SimpleDataFormat。有人纠正我,如果有一个更简单的方法,使一个月的日历,虽然,我这样做的代码现在,我不那么肯定 import java.text.DateFormatSymbols; public String getMonth(int month) { return new DateFormatSymbol

我得到一个整数,我需要转换为不同地区的月份名称:

美国语言环境示例:
1->1月
2月->2月

区域设置es mx示例:
1->Enero

2->Febrero

我会使用SimpleDataFormat。有人纠正我,如果有一个更简单的方法,使一个月的日历,虽然,我这样做的代码现在,我不那么肯定

import java.text.DateFormatSymbols;
public String getMonth(int month) {
    return new DateFormatSymbols().getMonths()[month-1];
}
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;


public String formatMonth(int month, Locale locale) {
    DateFormat formatter = new SimpleDateFormat("MMMM", locale);
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    calendar.set(Calendar.MONTH, month-1);
    return formatter.format(calendar.getTime());
}

我会这样做的。我将把
int月的范围检查留给您

import java.text.DateFormatSymbols;

public String formatMonth(int month, Locale locale) {
    DateFormatSymbols symbols = new DateFormatSymbols(locale);
    String[] monthNames = symbols.getMonths();
    return monthNames[month - 1];
}

使用SimpleDataFormat

import java.text.SimpleDateFormat;

public String formatMonth(String month) {
    SimpleDateFormat monthParse = new SimpleDateFormat("MM");
    SimpleDateFormat monthDisplay = new SimpleDateFormat("MMMM");
    return monthDisplay.format(monthParse.parse(month));
}


formatMonth("2"); 

结果:2月

很明显,Android 2.2中存在SimpleDataFormat错误

import java.text.SimpleDateFormat;

public String formatMonth(String month) {
    SimpleDateFormat monthParse = new SimpleDateFormat("MM");
    SimpleDateFormat monthDisplay = new SimpleDateFormat("MMMM");
    return monthDisplay.format(monthParse.parse(month));
}


formatMonth("2"); 
为了使用月份名称,您必须在资源中自己定义它们:

<string-array name="month_names">
    <item>January</item>
    <item>February</item>
    <item>March</item>
    <item>April</item>
    <item>May</item>
    <item>June</item>
    <item>July</item>
    <item>August</item>
    <item>September</item>
    <item>October</item>
    <item>November</item>
    <item>December</item>
</string-array>

您需要将LLLL用于独立月份名称。这在
SimpleDataFormat
文档中有记录,例如:

SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );
tl;博士 java.time 由于Java 1.8(或带有的1.7和1.6),您可以使用:

Month.of(integerMonth).getDisplayName(TextStyle.FULL_STANDALONE, locale);

请注意,
integerMonth
是以1为基础的,即1表示一月。1月至12月(即仅公历)的范围始终为1至12。

在某些Android设备中,使用DateFormatSymbols类的getMonthName方法按名称获取月份时会出现问题。我通过以下方式解决了这个问题:

在String_array.xml中

<string-array name="year_month_name">
    <item>January</item>
    <item>February</item>
    <item>March</item>
    <item>April</item>
    <item>May</item>
    <item>June</item>
    <item>July</item>
    <item>August</item>
    <item>September</item>
    <item>October</item>
    <item>November</item>
    <item>December</item>
    </string-array>

一月
二月
前进
四月
也许
六月
七月
八月
九月
十月
十一月
十二月
在Java类中,只需按如下方式调用此数组:

public String[] getYearMonthName() {
        return getResources().getStringArray(R.array.year_month_names);
        //or like 
       //return cntx.getResources().getStringArray(R.array.month_names);
    } 

      String[] months = getYearMonthName(); 
           if (i < months.length) {
            monthShow.setMonthName(months[i] + " " + year);

            }
public字符串[]getYearMonthName(){
返回getResources().getStringArray(R.array.year\u month\u名称);
//或者
//返回cntx.getResources().getStringArray(R.array.month_name);
} 
字符串[]月=getYearMonthName();
如果(i<月长){
monthShow.setMonthName(月[i]+“”+年);
}
快乐编码:)

tl;博士
java.time.Month
现在在java.time类中更容易实现,它取代了这些麻烦的旧遗留日期时间类

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

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

Month month = Month.of( 2 );  // 2 → February.
要求对象生成一个字符串

调整以指定名称的长度或缩写。请注意,在某些语言(非英语)中,如果单独使用或作为完整日期的一部分使用,月份名称会有所不同。因此,每个文本样式都有一个独立的变量

指定要确定的参数:

  • 翻译时应该使用哪种人类语言
  • 什么样的文化规范应该决定缩写、标点和大写等问题
例如:

Locale l = new Locale( "es" , "MX" );
String output = Month.FEBRUARY.getDisplayName( TextStyle.SHORT_STANDALONE , l );  // Or Locale.US, Locale.CANADA_FRENCH. 

名称→ <代码>月份
对象 仅供参考,转到另一个方向(解析月份字符串的名称以获得
month
enum对象)不是内置的。您可以编写自己的类来这样做。下面是我在这门课上的快速尝试。使用风险自负。我没有认真考虑这个代码,也没有进行任何认真的测试

用法

Month m = MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ) ;  // Month.JANUARY
代码

package com.basilbourque.example;
导入org.jetbrains.annotations.NotNull;
导入org.jetbrains.annotations.Nullable;
导入java.time.Month;
导入java.time.format.TextStyle;
导入java.util.ArrayList;
导入java.util.List;
导入java.util.Locale;
//对于某些语言中给定的月份名称,请确定匹配的`java.time.month`enum对象。
//此类与'Month.getDisplayName'相反,后者为给定的'Month'对象生成本地化字符串。
//用法…MonthDelocalizer.of(Locale.CANADA\u FRENCH).parse(“janvier”)→ 一月
//假定“FormatStyle.FULL”表示没有缩写的名称。
//关于'java.time.Month'枚举:https://docs.oracle.com/javase/9/docs/api/java/time/Month.html
//使用风险自负。没有保证或担保的。没有执行任何严重的测试或代码审查。
公共类MonthDelocalizer
{
@NotNull
私人场所;
@NotNull
private ListmonthNames,monthnamestandalone;//某些语言对不带日期上下文的“独立”月份名称使用另一种拼写。
//构造函数.Private,用于静态工厂方法。
专用MonthDelocalizer(@NotNull语言环境)
{
this.locale=locale;
//填充一对数组,每个数组都有已翻译的月份名称。
int countMonthsInYear=12;//一年中有十二个月。
this.monthNames=新阵列列表(countMonthsInYear);
this.monthnamestandlone=新阵列列表(countMonthsInYear);
for(int i=1;i 0)?Month.of(ordinal):null;//如果命中,请确定'Month'枚举对象。否则返回null。
if(null==m)
{
抛出新的java.lang.IllegalArgumentException(“传递的月份名称:“+input+””对区域设置无效:“+this.locale.toString());
}
返回m;
}
//`Object`类重写。
@凌驾
公共布尔等于(对象o)
{
如果(this==o)返回true;
如果(o==null | | getClass()!=o.getClass())返回false;
MonthDelocalizer that=(MonthDelocalizer)o;
返回locale.equals(that.locale);
}
@凌驾
公共整数哈希代码()
{
返回locale.hashCode();
}
公共静态void main(字符串[]args)
{
//用法示例:
MonthDelocalizer monthDelocJapan=MonthDelocalizer.of(Locale.JAPAN);
尝试
{
月份m=monthDelocJapan.parse(“粉红大象”);//输入无效。
}捕获(IllegalArgumentException e)
{
//…处理错误
System.out.println(“错误:+e.getLocalizedMessage());
}
//忽略异常。(不推荐)
if(MonthDelocalizer.of(Locale.CANADA_FRENCH).parse(“janvier”).equals(Month.一月)
Month month = Month.of( 2 );  // 2 → February.
Locale l = new Locale( "es" , "MX" );
String output = Month.FEBRUARY.getDisplayName( TextStyle.SHORT_STANDALONE , l );  // Or Locale.US, Locale.CANADA_FRENCH. 
Month m = MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ) ;  // Month.JANUARY
package com.basilbourque.example;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.time.Month;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

// For a given name of month in some language, determine the matching `java.time.Month` enum object.
// This class is the opposite of `Month.getDisplayName` which generates a localized string for a given `Month` object.
// Usage… MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ) → Month.JANUARY
// Assumes `FormatStyle.FULL`, for names without abbreviation.
// About `java.time.Month` enum: https://docs.oracle.com/javase/9/docs/api/java/time/Month.html
// USE AT YOUR OWN RISK. Provided without guarantee or warranty. No serious testing or code review was performed.
public class MonthDelocalizer
{
    @NotNull
    private Locale locale;

    @NotNull
    private List < String > monthNames, monthNamesStandalone; // Some languages use an alternate spelling for a “standalone” month name used without the context of a date.

    // Constructor. Private, for static factory method.
    private MonthDelocalizer ( @NotNull Locale locale )
    {
        this.locale = locale;

        // Populate the pair of arrays, each having the translated month names.
        int countMonthsInYear = 12; // Twelve months in the year.
        this.monthNames = new ArrayList <>( countMonthsInYear );
        this.monthNamesStandalone = new ArrayList <>( countMonthsInYear );

        for ( int i = 1 ; i <= countMonthsInYear ; i++ )
        {
            this.monthNames.add( Month.of( i ).getDisplayName( TextStyle.FULL , this.locale ) );
            this.monthNamesStandalone.add( Month.of( i ).getDisplayName( TextStyle.FULL_STANDALONE , this.locale ) );
        }
//        System.out.println( this.monthNames );
//        System.out.println( this.monthNamesStandalone );
    }

    // Constructor. Private, for static factory method.
    // Personally, I think it unwise to default implicitly to a `Locale`. But I included this in case you disagree with me, and to follow the lead of the *java.time* classes. --Basil Bourque
    private MonthDelocalizer ( )
    {
        this( Locale.getDefault() );
    }

    // static factory method, instead of  constructors.
    // See article by Dr. Joshua Bloch. http://www.informit.com/articles/article.aspx?p=1216151
    // The `Locale` argument determines the human language and cultural norms used in de-localizing input strings.
    synchronized static public MonthDelocalizer of ( @NotNull Locale localeArg )
    {
        MonthDelocalizer x = new MonthDelocalizer( localeArg ); // This class could be optimized by caching this object.
        return x;
    }

    // Attempt to translate the name of a month to look-up a matching `Month` enum object.
    // Returns NULL if the passed String value is not found to be a valid name of month for the human language and cultural norms of the `Locale` specified when constructing this parent object, `MonthDelocalizer`.
    @Nullable
    public Month parse ( @NotNull String input )
    {
        int index = this.monthNames.indexOf( input );
        if ( - 1 == index )
        { // If no hit in the contextual names, try the standalone names.
            index = this.monthNamesStandalone.indexOf( input );
        }
        int ordinal = ( index + 1 );
        Month m = ( ordinal > 0 ) ? Month.of( ordinal ) : null;  // If we have a hit, determine the `Month` enum object. Else return null.
        if ( null == m )
        {
            throw new java.lang.IllegalArgumentException( "The passed month name: ‘" + input + "’ is not valid for locale: " + this.locale.toString() );
        }
        return m;
    }

    // `Object` class overrides.

    @Override
    public boolean equals ( Object o )
    {
        if ( this == o ) return true;
        if ( o == null || getClass() != o.getClass() ) return false;

        MonthDelocalizer that = ( MonthDelocalizer ) o;

        return locale.equals( that.locale );
    }

    @Override
    public int hashCode ( )
    {
        return locale.hashCode();
    }

    public static void main ( String[] args )
    {
        // Usage example:
        MonthDelocalizer monthDelocJapan = MonthDelocalizer.of( Locale.JAPAN );
        try
        {
            Month m = monthDelocJapan.parse( "pink elephant" ); // Invalid input.
        } catch ( IllegalArgumentException e )
        {
            // … handle error
            System.out.println( "ERROR: " + e.getLocalizedMessage() );
        }

        // Ignore exception. (not recommended)
        if ( MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ).equals( Month.JANUARY ) )
        {
            System.out.println( "GOOD - In locale "+Locale.CANADA_FRENCH+", the input ‘janvier’ parses to Month.JANUARY." );
        }
    }
}
DateFormatSymbols.getInstance().getMonths()[view.getMonth()] 
public static String convertnumtocharmonths(int m){
         String charname=null;
         if(m==1){
             charname="Jan";
         }
         if(m==2){
             charname="Fev";
         }
         if(m==3){
             charname="Mar";
         }
         if(m==4){
             charname="Avr";
         }
         if(m==5){
             charname="Mai";
         }
         if(m==6){
             charname="Jun";
         }
         if(m==7){
             charname="Jul";
         }
         if(m==8){
             charname="Aou";
         }
         if(m==9){
             charname="Sep";
         }
         if(m==10){
             charname="Oct";
         }
         if(m==11){
             charname="Nov";
         }
         if(m==12){
             charname="Dec";
         }
         return charname;
     }
fun Int.toMonthName(): String {
    return DateFormatSymbols().months[this]
}
calendar.get(Calendar.MONTH).toMonthName()