質問

取得し整数としに変換する必要がある月名様々なロケール:

とえばロケールブックマークグループを開くとき:
1->月
2->月

例esロケール-mx:
1->Enero
2->Febrero

役に立ちましたか?

解決

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

他のヒント

スタンドアロンの月名にはLLLLを使用する必要があります。これは、次のようなSimpleDateFormatドキュメントに記載されています。

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

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

java.time

Java 1.8(または1.7 <!> amp; 1.6以降、 ThreeTen-Backport > )これを使用できます:

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

integerMonthは1から始まります。つまり、1は1月です。 1月から12月の範囲は常に1から12です(つまり、グレゴリオ暦のみ)。

これが私がやる方法です。 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];
}

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

結果:2月

どうやら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;
}

tl;dr

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

やってるドキュメンテーションシステム.時間の授業とsupplantこれらの面倒が多いユーザーの日時ます。

Month enum定数十オブジェは、毎月.

のヶ月間で整理1-12月ました。

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

のオブジェクトを生成する文字列の 名前を自動的に局在.

を調整し TextStyle 指定長または略称はそのままにしてます。るということに注意してくださいくつかの言語(英語)の月の名前が異なり使用する場合には完全な日です。それを読取った文字を、テキスト形式は、 …_STANDALONE バリアントだ。

指定 Locale の決定:

  • 人間の言語を採用すべきである。
  • 何文化の規範を決定すべきであるなどの問題、略語句読点、資本化率を有している。

例:

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

コードです。

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.時間

java.時間 枠組みがJava8以降である。これらのクラスsupplantの面倒古 レガシー 日付-時間の授業など java.util.Date, Calendar, & SimpleDateFormat.

Joda-時間 プロジェクトは、 メンテナンスモード,助言への移行 java.時間 ます。

詳細は、 Oracleのチュートリアル.検索スタックオーバーフローのための多くの例で説明しています。仕様 JSR310.

お取引所 java.時間 オブジェクトを直接データベース.を使用 JDBCドライバ 対応 JDBC4.2 以降となります。が必要ない文字列が必要ない java.sql.* ます。

入手先のjava.時間の授業で

  • Java SE8, Java SE9, 以降、
    • ですのでお問い合わせ下さい。
    • 一部の標準のJava APIでは、同梱の実装です。
    • Java9を追加し若干の特徴と問題を修正
  • Java SE6Java SE7
  • Android
    • 次期バージョン以降でも、Androidのバンドルの実装は、java.時間ます。
    • それ以前のAndroid(<26)、 ThreeTenABP プロジェクトに対応 ThreeTen-Backport (上).見 使い方ThreeTenABP....

ThreeTenインストール プロジェクトextends java.時間を追加します。このプロジェクトには、立地のためには、将来的な追加java.ます。すべての授業などはこちら Interval, YearWeek, YearQuarter, は、 以上.

getFormatNameメソッドにDateFormatSymbolsクラスを使用して、一部のAndroidデバイスで名前ごとに月を表示する場合に問題があります。次の方法でこの問題を解決しました:

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 static void main(String[] args) {
    SimpleDateFormat format = new SimpleDateFormat("MMMMM", new Locale("en", "US"));
    System.out.println(format.format(new Date()));
}

行を挿入するだけ

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

トリックを行います。

これを非常に簡単な方法で使用して、独自の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;
     }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top