Question

Je reçois un entier et j'ai besoin de convertir en noms de mois dans différents environnements locaux:

Exemple de locale en-us:
1 - & Gt; Janvier
2 - & Gt; Février

Exemple de locale es-mx:
1 - & Gt; Enero
2 - & Gt; Febrero

Était-ce utile?

La solution

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

Autres conseils

Vous devez utiliser LLLL pour les noms de mois autonomes. ceci est documenté dans la SimpleDateFormat documentation, telle que:

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

J'utiliserais SimpleDateFormat. Quelqu'un me corrige s’il existe un moyen plus facile de créer un calendrier mensuel, c’est ce que je fais maintenant dans le code et je ne suis pas sûr.

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

Depuis Java 1.8 (ou 1.7 & et 1.6; avec le ThreeTen-Backport ) vous pouvez utiliser ceci:

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

Notez que integerMonth est basé sur 1, c’est-à-dire que 1 correspond à janvier. La plage est toujours comprise entre 1 et 12 janvier à décembre (calendrier grégorien uniquement).

Voici comment je le ferais. Je laisserai la vérification de la plage sur le int month qui vous convient.

import java.text.DateFormatSymbols;

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

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

Résultat: février

Apparemment, dans Android 2.2, un simple problème avec SimpleDateFormat.

Pour utiliser les noms de mois, vous devez les définir vous-même dans vos ressources:

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

Et utilisez-les ensuite dans votre code comme ceci:

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

Il est beaucoup plus facile de faire maintenant dans les classes java.time qui supplantent ces anciennes classes de date / heure problématiques.

Le Month enum définit une douzaine d'objets, un pour chaque mois.

Les mois sont numérotés de 1 à 12 pour la période de janvier à décembre.

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

Demandez à l'objet de générer une chaîne du nom du mois, automatiquement localisé .

Ajustez le TextStyle pour spécifier combien de temps ou abrégé vous voulez le nom. Notez que dans certaines langues (pas l'anglais), le nom du mois varie s'il est utilisé seul ou dans le cadre d'une date complète. Ainsi, chaque style de texte a une …_STANDALONE variante.

Spécifiez un Locale . pour déterminer:

  • Quelle langue humaine doit être utilisée pour la traduction.
  • Quelles normes culturelles devraient trancher des questions telles que l'abréviation, la ponctuation et la capitalisation.

Exemple:

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

Nom & # 8594; java.util.Date objet

Pour votre information, aller dans l'autre sens (analyser une chaîne de nom de mois pour obtenir un objet Calendar enum) n'est pas intégré. Vous pouvez écrire votre propre classe pour le faire. Voici ma tentative rapide d'une telle classe. Utilisez-le à vos risques et périls . Je n'ai pas pensé sérieusement à ce code ni à aucun test sérieux.

Utilisation.

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

Code.

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

À propos de java.time

Le java.time est intégré à Java 8 et aux versions ultérieures. Ces classes supplantent les anciennes classes de date-heure héritées , telles que SimpleDateFormat , java.sql.* , & amp; Interval .

Le projet Joda-Time , maintenant dans < a href = "https://en.wikipedia.org/wiki/Maintenance_mode" rel = "nofollow noreferrer"> mode de maintenance , conseille la migration vers le classes java.time .

Pour en savoir plus, consultez le Didacticiel Oracle . . Et recherchez Stack Overflow pour de nombreux exemples et explications. La spécification est JSR 310 .

Vous pouvez échanger des objets java.time directement avec votre base de données. Utilisez un pilote JDBC conforme à JDBC 4.2 ou version ultérieure. Pas besoin de chaînes, pas besoin de YearWeek classes.

Où obtenir les classes java.time?

Le projet ThreeTen-Extra étend le java.time avec des cours supplémentaires. Ce projet est un terrain d’essai pour d’éventuels ajouts à java.time. Vous pouvez trouver ici des classes utiles telles que YearQuarter , <=> , <=> , et plus .

Il existe un problème lorsque vous utilisez la classe DateFormatSymbols pour que sa méthode getMonthName obtienne Mois par Nom, il affiche Mois par Numéro sur certains appareils Android. J'ai résolu ce problème en procédant de la manière suivante:

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

En classe Java, appelez simplement ce tableau comme suit:

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

            }

Happy Coding:)

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

Insérez simplement la ligne

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

fera l'affaire.

Essayez d’utiliser cette méthode très simplement et appelez-la comme votre propre fonction

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;
     }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top