Les Snippets

Connexion

Récupérer le numéro du mois à partir de son nom

Niveau requis pour utiliser/comprendre cette source : 1 ( Débutant )
Créé le 02/07/2007 21:20:19 et initié par PCPT [Liste]
Date de mise à jour : 19/12/2007 17:47:53
Vue : 7191
Catégorie(s) : Date & Heure, Chaîne de caractères
Langages dispo pour ce code :
- VB6, VBA
- VB6, VBA
- Javascript
- Java
- PHP 3, PHP 4, PHP 5
- Delphi 5
- Delphi 5
- Delphi 5
- VB6, VBA
- PHP 5
- PHP 5



Langage : VB6 , VBA
Date ajout : 02/07/2007
Posté par PCPT [Liste]
Function GetMonthNum(ByVal sMonth As String) As Integer
    Select Case LCase$(sMonth)
        Case "janv""janvier":                     GetMonthNum = 1
        Case "févr""février""fevr""fevrier":  GetMonthNum = 2
        Case "mars":                                GetMonthNum = 3
        Case "avr""avril":                        GetMonthNum = 4
        Case "mai":                                 GetMonthNum = 5
        Case "juin":                                GetMonthNum = 6
        Case "juil""juillet":                     GetMonthNum = 7
        Case "août""aout":                        GetMonthNum = 8
        Case "sept""septembre":                   GetMonthNum = 9
        Case "oct""octobre":                      GetMonthNum = 10
        Case "nov""novembre":                     GetMonthNum = 11
        Case "déc""décembre""dec""decembre":  GetMonthNum = 12
        Case Else:                                  GetMonthNum = 0
    End Select
End Function

Langage : VB6 , VBA
Date ajout : 03/07/2007
Posté par mortalino [Liste]
Function GetMonthNum(ByVal sMonth As String) As Integer
    Dim As Integer
GetMonthNum = 0
For i = To 12
    If InStr(1, _
        Replace(Replace(Format$("01/" Format(CStr(i), "00") & "/00""mmmm"), "é""e"), "û""u"), _
        LCase$(Replace(Replace(sMonth, "é""e"), "û""u")), vbTextCompare) Then GetMonthNum = i: Exit For
Next i
End Function
Remarque :
Beaucoup d'imbrications, mais voici une autre soluce ;)
Langage : Javascript
Date ajout : 07/07/2007
Posté par yousfane [Liste]
function GetMonthNum(sMonth)
{
    switch (sMonth)
    {
        case "janv" : 
        case "janvier" :                     
            return 1;
        break;
        case "févr" : 
        case "février" : 
        case "fevr" : 
        case "fevrier" :  
            return 2;
        break;
        case "mars":                               
            return 3;
        break;
        case "avr" : 
        case "avril" :                        
            return 4;
        break;
        case "mai":                                 
            return 5;
        break;
        case "juin":                                
            return 6;
        break;
        case "juil" : 
        case "juillet":                     
            return 7;
        break;
        case "août" : 
        case "aout":                        
            return 8;
        break;
        case "sept" : 
        case "septembre":                   
            return 9;
        break;
        case "oct" : 
        case "octobre":                      
            return 10;
        break;
        case "nov" : 
        case "novembre":                     
            return 11;
        break;
        case "déc" : 
        case "décembre" : 
        case "dec" : 
        case "decembre":  
            return 12;
        break;
        default:                                  
            return 0;
        break;
    }
}
Langage : Java
Date ajout : 07/07/2007
Posté par yousfane [Liste]
public static int GetMonthNum(String sMonth)
{
        if (sMonth == "janv" || sMonth == "janvier")
        {
            return 1;
        }
        else if (sMonth == "févr" || sMonth == "février" || sMonth == "fevr" || sMonth == "fevrier") 
        {
            return 2;
        }
        else if (sMonth == "mars")                              
        {
            return 3;
        }
        else if (sMonth == "avr" || sMonth == "avril")                     
        {
            return 4;
        }
        else if (sMonth == "mai")                                
        {
            return 5;
        }
        else if (sMonth == "juin")                                
        {
            return 6;
        }
        else if (sMonth == "juil" || sMonth == "juillet")                    
        {
            return 7;
        }
        else if (sMonth == "août" || sMonth == "aout")                      
        {
            return 8;
        }
        else if (sMonth == "sept" || sMonth == "septembre")                   
        {
            return 9;
        }
        else if (sMonth == "oct" || sMonth == "octobre")                    
        {
            return 10;
        }
        else if (sMonth == "nov" || sMonth == "novembre")                   
        {
            return 11;
        }
        else if (sMonth == "déc" || sMonth == "décembre" || sMonth == "dec" || sMonth == "decembre")   
        {
            return 12;
        }
        else                                  
        {
            return 0;
        }
}
Langage : PHP 3 , PHP 4 , PHP 5
Date ajout : 23/09/2007
Posté par spoonisback [Liste]
<?php
    function GetMonthNum($month)
    {
        switch($month)
        {
            case('janv'):
            case('janvier'):
            return 1;
            break;    
            
            case('fevr'):
            case('fevrier'):
            return 2;
            break;
            
            case('mars'):
            return 3;
            break;
            
            case('avri'):
            case('avril'):
            return 4;
            break;
            
            case('mai'):
            return 5;
            break;
            
            case('juin'):
            return 6;
            break;
            
            case('juil'):
            case('juillet'):
            return 7;
            break;
            
            case('aout'):
            return 8;
            break;
            
            case('sept'):
            case('septembre'):
            return 9;
            break;
            
            case('octo'):
            case('octobre'):
            return 10;
            break;
            
            case('nove'):
            case('novembre'):
            return 11;
            break;
            
            case('dece'):
            case('decembre'):
            return 12;
              break;
            
            default:
            return 0;
        }
    }
?> 
Remarque :
Exemple d'appel :
$numero_mois = GetMonthNum("janvier");
Langage : Delphi 5
Date ajout : 30/09/2007
Posté par Guillemouze [Liste]
const NomsMois : array[0..1] of array[1..12] of string =
  (
   ('janvier', 'fevrier', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'decembre'),
   ('janv'   ,'fevr'    , 'mars', 'avr'  , 'mai', 'juin', 'juil'   , 'aout', 'sept'     , 'oct'    , 'nov'     , 'dec'     )
  );
type TMoisNo = 0..12;
function GetMonthNum(MonthName: String): TMoisNo;
var
  i, j: integer;
begin
  MonthName := LowerCase(StringReplace(MonthName, 'é', 'e',  [rfReplaceAll, rfIgnoreCase]));
  Result := 0;
  i := Low(NomsMois);
  while (Result = 0) and (i <= High(NomsMois)) do
  begin
    j := Low(NomsMois[i]);
    while (Result = 0) and (j <= High(NomsMois[i])) do
    begin
      if NomsMois[i][j] = MonthName then
        Result := j;
      Inc(j);
    end;
    Inc(i);
  end;
end;

Langage : Delphi 5
Date ajout : 03/10/2007
Posté par japee [Liste]
DateMAJ : 03/10/2007
function GetMonthNum(Month: string): Word;
const
  ArrTypeInfo: array[0..1, 1..13] of LCTYPE = (
   (LOCALE_SMONTHNAME1,
    LOCALE_SMONTHNAME2,
    LOCALE_SMONTHNAME3,
    LOCALE_SMONTHNAME4,
    LOCALE_SMONTHNAME5,
    LOCALE_SMONTHNAME6,
    LOCALE_SMONTHNAME7,
    LOCALE_SMONTHNAME8,
    LOCALE_SMONTHNAME9,
    LOCALE_SMONTHNAME10,
    LOCALE_SMONTHNAME11,
    LOCALE_SMONTHNAME12,
    LOCALE_SMONTHNAME13),
   (LOCALE_SABBREVMONTHNAME1,
    LOCALE_SABBREVMONTHNAME2,
    LOCALE_SABBREVMONTHNAME3,
    LOCALE_SABBREVMONTHNAME4,
    LOCALE_SABBREVMONTHNAME5,
    LOCALE_SABBREVMONTHNAME6,
    LOCALE_SABBREVMONTHNAME7,
    LOCALE_SABBREVMONTHNAME8,
    LOCALE_SABBREVMONTHNAME9,
    LOCALE_SABBREVMONTHNAME10,
    LOCALE_SABBREVMONTHNAME11,
    LOCALE_SABBREVMONTHNAME12,
    LOCALE_SABBREVMONTHNAME13));
var
  i, j: Integer;
  LCData : array[0..255] of Char;
begin
  Result := 0;
  Month := AnsiLowerCase(Month);
  for i := 0 to 1 do
    for j := 1 to 13 do
    begin
      GetLocaleInfo(LOCALE_SYSTEM_DEFAULT,
                    ArrTypeInfo[i, j],
                    LCData,
                    SizeOf(LCData) - 1);
      if (Month = LCData) and (LCData <> '') then
      begin
        Result := j;
        Break
      end;
    end;
end;
Remarque :
Version basée sur les informations locales du système.
Les mois sont admis sous leur forme courte ou longue, minuscule ou majuscule.
Fait appel à l'API GetLocaleInfo().
Adapté donc à la langue du système d'exploitation.
Prend en compte un éventuel 13ème mois.
Pour mémoire, formes courtes françaises admises par l'OS :
janv., févr., mars, avr., mai, juin, juil., août, sept., oct., nov., déc.
Langage : Delphi 5
Date ajout : 03/10/2007
Posté par cirec [Liste]
Function GetMonthNum(Month: String): Word;
Var I : Integer;
    PMonth, PShortMonth, PLongMonth : PChar;
Begin
  Result := 0;
  PMonth := PChar(Month);
  For I := 1 To 12 Do Begin
    PShortMonth := PChar(ShortMonthNames[I]);
    PLongMonth := PChar(LongMonthNames[I]);
    If (CompareString(LOCALE_USER_DEFAULT, SORT_STRINGSORT Or NORM_IGNORECASE
       Or NORM_IGNORENONSPACE Or NORM_IGNORESYMBOLS, PMonth, -1, PShortMonth,
       -1) = CSTR_EQUAL) Or (CompareString(LOCALE_USER_DEFAULT, SORT_STRINGSORT
       Or NORM_IGNORECASE Or NORM_IGNORENONSPACE Or NORM_IGNORESYMBOLS, PMonth,
       -1, PLongMonth, -1) = CSTR_EQUAL) Then
    Begin
      Result := I;
      Break;
    End;
  End;
End;


Remarque :
Cette fonction accèpte toutes les langues
la comparaison ne tiens pas compte des accents ni des caractères spéciaux
ni de la case.
"Déc", "dec", "dèc", "Dec.", "[Dec.]", "[  Dec.  ]"  -------->> donne 12
"Aout", "aôut", "août", "aout", "[Aout]", "[  Aout  ]" ----->> donne 8
Langage : VB6 , VBA
Date ajout : 09/11/2007
Posté par jrivet [Liste]
DateMAJ : 09/11/2007
Private Sub Form_Load()
   Debug.Print GetMonthNum("janv")
   Debug.Print GetMonthNum("janvier")
   Debug.Print GetMonthNum("févr")
   Debug.Print GetMonthNum("février")
   Debug.Print GetMonthNum("mars")
   Debug.Print GetMonthNum("avril")
   Debug.Print GetMonthNum("avr")
   Debug.Print GetMonthNum("mai")
   Debug.Print GetMonthNum("juin")
   Debug.Print GetMonthNum("juil")
   Debug.Print GetMonthNum("juillet")
End Sub 
Public Function GetMonthNum(MName As String) As Integer On Error Resume Next    'NE FONCTIONNE QUE SI LES CARACTERE ACCENTUES SONT PRESENTS    'D ou On Error Resume Next    GetMonthNum = Month(Format("01 " & MName & " " & Year(Date), "dd mmmm yyyy")) On Error GoTo 0 End Function
Remarque :
Petite variante en VB6. comme insrit dans le commentaire ne fonctionne que si les caractères accentués sont présents.
Langage : PHP 5
Date ajout : 06/12/2007
Posté par neigedhiver [Liste]
DateMAJ : 19/12/2007
<?php
function NumeroDuMois($sMois) {
    setlocale(LC_TIME, 'fr_FR');
    $data = strptime($sMois, '%B');
    return $data ? ($data['tm_mon'] + 1) : false;
}
?>
/**
* Modifié par Malalam
* Version fonctionnant sous Windows
* paramètre : mois numérique, de 1 à 12, sous la forme d'un entier. Sinon la fonction renvoie le mois courant.
* setlocale() dépend de la configuration du serveur, ses valeurs sont à tester (2d paramètre)
* date_default_timezone() est nécessaire sous la plupart des système si on ne veut pas sortir une erreur de niveau E_STRICT.
*/
<?php
function NumeroDuMois($iMois = null) {
    date_default_timezone_set('Europe/Paris');
    setlocale(LC_TIME, NULL);
    if(!is_null ($iMois) && is_int($iMois) && $iMois > 0 && $iMois < 13) {
        return strftime('%B', strtotime('2007/'.$iMois.'/1'));
    } 
    return strftime('%B');
}
echo NumeroDuMois(5); 
?>

Remarque :
Ne fonctionne pas sur Windows et nécessite PHP 5.1 minimum.

L'argument est le nom du mois dans la langue spécifiée avec setlocale(). Il est insensible à la casse, avec ou sans accents et peut même être incomplet. Ces lignes renvoient la même chose :
NumeroDuMois('dec');
NumeroDuMois('Déc');
NuméroDuMois('Décembre');
Langage : PHP 5
Date ajout : 19/12/2007
Posté par malalam [Liste]
DateMAJ : 19/12/2007
<?php
date_default_timezone_set('Europe/Paris');
setlocale(LC_TIME, NULL);
echo strftime('%B');
?>
Remarque :
setlocale() est à tester selon le serveur, la valeur nécessaire peut varier. Cette version fonctionne sous Windows.

Snippets en rapport avec : Mois, Date, Numéro



Codes sources en rapport avec : Mois, Date, Numéro

{Visual Basic, VB6, VB.NET, VB 2005} CALENDRIER SOUS VBA (EXCEL)
Ce code permet de sélectionner une date dans un calendrier Le nombre de jour par mois et défini Le...

{Delphi} GESTION DE CALENDRIER DYNAMIQUE
Dans n'importe quelle application de gestion vous avez besoin d'un calendrier d'activité. Et bien c...

{SQL} DERNIER JOUR DU MOIS, OU DE LA SEMAINE
J'ai mis ces fonctions toujour utiles dans CODIX (les snippets) mais l'un est faut et on peut pas le...

{Javascript / DHTML} NUMERO DE LA SEMAINE
Trois méthodes pour l'objet Date, une pour connaître le numéro du jour dans l'année, une pour obteni...

{Delphi} GETYMDBETWEEN() - DIFFÉRENCE ENTRE 2 DATES (ANNÉES, MOIS, JOURS)
Calcule la différence entre deux dates au format TDateTime. Différence comptée en Ans, Jours, Mois....

{PHP} CALENDRIER - FLOPTWO
Calendrier - floptwo : Il s'agit d'un script qui réalise un calendrierà partir de la date du jour. ...

{Visual Basic, VB6, VB.NET, VB 2005} VBA EXCEL TRANSFORME UNE DATE ENREGISTRÉE AU FORMAT ANGLAIS (BOGUE D'INVERSION MOIS / JOUR)
A ma grande surprise, je constate qu'il existe encore des fichiers Excel contenant l'anomalie liée a...

{PHP} DIFFÉRENCE ENTRE DEUX DATE (LISTE RÉCUPÉRÉE DANS UN TABLEAU)
Salut les codeurs fou ! Je développe actuellement une petite appli pour faire mes comptes, et j'en ...

{Javascript / DHTML} LA DATE TOUTE SIMPLE.
Il permet de mettre sur votre site la date sans pub....

{PHP} CALENDRIER DU MOIS EN COURS
Le calendrier affiche le mois en cours, le jour est affiché en gras. Il suffit de copier le calque d...