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

时间:2009-06-24 14:00:51

标签: java date locale

我得到一个整数,我需要在各种语言环境中转换为月份名称:

locale en-us示例:
1 - >一月
2 - >二月

语言环境es-mx的示例:
1 - > Enero
2 - > Febrero

13 个答案:

答案 0 :(得分:193)

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

答案 1 :(得分:32)

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

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

答案 2 :(得分:16)

我会使用SimpleDateFormat。如果有更简单的方法制作蒙太奇的日历,有人会纠正我,我现在在代码中这样做,我不太确定。

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

答案 3 :(得分:13)

这是我将如何做到的。我会将int month的范围检查留给您。

import java.text.DateFormatSymbols;

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

答案 4 :(得分:12)

java.time

自Java 1.8(或带有ThreeTen-Backport的1.7& 1.6)以来,您可以使用它:

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

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

答案 5 :(得分:10)

使用SimpleDateFormat。

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

结果:二月

答案 6 :(得分:7)

显然在Android 2.2中存在SimpleDateFormat的错误。

要使用月份名称,您必须自己在资源中定义它们:

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

然后在你的代码中使用它们:

/**
 * Get the month name of a Date. e.g. January for the Date 2011-01-01
 * 
 * @param date
 * @return e.g. "January"
 */
public static String getMonthName(Context context, Date date) {

    /*
     * Android 2.2 has a bug in SimpleDateFormat. Can't use "MMMM" for
     * getting the Month name for the given Locale. Thus relying on own
     * values from string resources
     */

    String result = "";

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    int month = cal.get(Calendar.MONTH);

    try {
        result = context.getResources().getStringArray(R.array.month_names)[month];
    } catch (ArrayIndexOutOfBoundsException e) {
        result = Integer.toString(month);
    }

    return result;
}

答案 7 :(得分:6)

TL;博士

/((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z0-9\&\.\/\?\:@\-_=#])*/g

Month.of( yourMonthNumber ) // Represent a month by its number, 1-12 for January-December. .getDisplayName( // Generate text of the name of the month automatically localized. TextStyle.SHORT_STANDALONE , // Specify how long or abbreviated the name of month should be. new Locale( "es" , "MX" ) // Locale determines (a) the human language used in translation, and (b) the cultural norms used in deciding issues of abbreviation, capitalization, punctuation, and so on. ) // Returns a String.

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

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

1月至12月的月份编号为1-12。

java.time.Month

要求对象生成name of the month, automatically localized的字符串。

调整TextStyle以指定您想要名称的长度或缩写。请注意,在某些语言(非英语)中,月份名称会有所不同,如果单独使用或作为完整日期的一部分使用。因此,每种文字样式都有Month month = Month.of( 2 ); // 2 → February. 变体。

指定Locale以确定:

  • 翻译应使用哪种人类语言。
  • 哪些文化规范应该决定缩写,标点符号和大小写等问题。

示例:

…_STANDALONE

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

仅供参考,向另一个方向(解析月份名称字符串以获取Month枚举对象)不是内置的。您可以编写自己的类来执行此操作。以下是我对这类课程的快速尝试。 使用风险自负。我没有认真考虑这个代码,也没有任何严肃的测试。

使用。

Month

代码。

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

关于 java.time

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

现在位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要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." ); } } } 类。

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuartermore

答案 8 :(得分:1)

当您使用DateFormatSymbols类为其getMonthName方法获取Month by Name时,在某些Android设备中显示Month by Number时会出现问题。我通过这种方式解决了这个问题:

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

            }

快乐编码:)

答案 9 :(得分:0)

    public static void main(String[] args) {
    SimpleDateFormat format = new SimpleDateFormat("MMMMM", new Locale("en", "US"));
    System.out.println(format.format(new Date()));
}

答案 10 :(得分:0)

只需插入行

DateFormatSymbols.getInstance().getMonths()[view.getMonth()] 

可以解决问题。

答案 11 :(得分:0)

尝试使用这种非常简单的方法,并像您自己的func一样调用它

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

答案 12 :(得分:0)

Kotlin扩展

fun Int.toMonthName(): String {
    return DateFormatSymbols().months[this]
}

用法

calendar.get(Calendar.MONTH).toMonthName()