IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

[C#][Calendar] Comment convertir correctement une date en un numéro de semaine ?


Sujet :

C#

  1. #1
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Avril 2006
    Messages
    42
    Détails du profil
    Informations personnelles :
    Localisation : France, Sarthe (Pays de la Loire)

    Informations forums :
    Inscription : Avril 2006
    Messages : 42
    Points : 39
    Points
    39
    Par défaut [C#][Calendar] Comment convertir correctement une date en un numéro de semaine ?
    Bonjour,

    Je veux convertir une date en numéro de semaine, mon code est les suivant :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    CultureInfo myCI = CultureInfo.CurrentCulture ;
    System.Globalization.Calendar myCal = myCI.Calendar;
     
    CalendarWeekRule CWR = myCI.DateTimeFormat.CalendarWeekRule;
    DayOfWeek FirstDOW = myCI.DateTimeFormat.FirstDayOfWeek;
    int numSemaine = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear
    (dateRef, CWR, FirstDOW );
    Le numéro de semaine est trop grand de 1.
    Exp : Pour la date 02/05/2006, il me retourne 19 et pas 18.


  2. #2
    Expert éminent
    Avatar de neguib
    Profil pro
    Inscrit en
    Mai 2005
    Messages
    3 627
    Détails du profil
    Informations personnelles :
    Âge : 63
    Localisation : Suisse

    Informations forums :
    Inscription : Mai 2005
    Messages : 3 627
    Points : 7 879
    Points
    7 879
    Par défaut
    Quelles sont les valeurs que tu obtiens pour CWR et FirstDOW ?
    Pour le bien de ceux qui vous lisent, ayez à coeur le respect du forum et de ses règles

  3. #3
    HPJ
    HPJ est déconnecté
    Membre averti

    Profil pro
    Inscrit en
    Mai 2003
    Messages
    260
    Détails du profil
    Informations personnelles :
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations forums :
    Inscription : Mai 2003
    Messages : 260
    Points : 364
    Points
    364
    Par défaut
    Après avoir testé ce code, je constate la même erreur qui est due au fait que CWR est égale à FirstDay alors qu'en France on utilise FirstFourDayWeek.
    Le CurrentCulture retourne donc la mauvaise valeur...
    Avant de poser une question, merci de chercher dans les rubriques suivantes:
    FAQ VB
    Tutoriaux VB
    Recherche avancée sur le forum

  4. #4
    Expert éminent
    Avatar de StormimOn
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mai 2005
    Messages
    2 593
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : France, Sarthe (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2005
    Messages : 2 593
    Points : 7 660
    Points
    7 660
    Par défaut
    C'est un problème du Framework je crois. Je me rappelle avoir lu un article là dessus l'année dernière, c'était avec le Framework 1 il me semble. La méthode GetWeekOfYear() ne renverra jamais un numéro correct (càd ISO 8601, enfin je crois), quelle que soit la culture. A priori le problème est toujours présent sous le Framework 2.

    Si je retrouve le lien de l'article je le posterais, mais j'avais toujours le code dans un coin, c'est le plus important

    Edit : j'ai retrouvé l'article ici.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
     
    private static int WeekNumber_Entire4DayWeekRule(DateTime date)
    {
        // Updated 2004.09.27. Cleaned the code and fixed a bug.
        // Compared the algorithm with code published here .
        // Tested code successfully against the other algorithm 
        // for all dates in all years between 1900 and 2100.
        // Thanks to Marcus Dahlberg for pointing out the deficient logic.
     
        // Calculates the ISO 8601 Week Number
        // In this scenario the first day of the week is monday, 
        // and the week rule states that:
        // [...] the first calendar week of a year is the one 
        // that includes the first Thursday of that year and 
        // [...] the last calendar week of a calendar year is 
        // the week immediately preceding the first 
        // calendar week of the next year.
        // The first week of the year may thus start in the 
        // preceding year
     
        const int JAN = 1;
        const int DEC = 12;
        const int LASTDAYOFDEC = 31;
        const int FIRSTDAYOFJAN = 1;
        const int THURSDAY = 4;
        bool ThursdayFlag = false;
     
        // Get the day number since the beginning of the year
        int DayOfYear = date.DayOfYear;
     
        // Get the numeric weekday of the first day of the 
        // year (using sunday as FirstDay)
        int StartWeekDayOfYear =
             (int)(new DateTime(date.Year, JAN, FIRSTDAYOFJAN)).DayOfWeek;
        int EndWeekDayOfYear =
             (int)(new DateTime(date.Year, DEC, LASTDAYOFDEC)).DayOfWeek;
     
        // Compensate for the fact that we are using monday
        // as the first day of the week
        if (StartWeekDayOfYear == 0)
            StartWeekDayOfYear = 7;
        if (EndWeekDayOfYear == 0)
            EndWeekDayOfYear = 7;
     
        // Calculate the number of days in the first and last week
        int DaysInFirstWeek = 8 - (StartWeekDayOfYear);
        int DaysInLastWeek = 8 - (EndWeekDayOfYear);
     
        // If the year either starts or ends on a thursday
        // it will have a 53rd week
        if (StartWeekDayOfYear == THURSDAY || EndWeekDayOfYear ==
     THURSDAY)
            ThursdayFlag = true;
     
        // We begin by calculating the number of FULL weeks
        // between the start of the year and our date.
        // The number is rounded up, so the smallest possible value is 0.
        int FullWeeks = (int)Math.Ceiling((DayOfYear - (DaysInFirstWeek)) /
     7.0);
     
        int WeekNumber = FullWeeks;
     
        // If the first week of the year has at least four days, then 
        // the actual week number for our date can be incremented by one.
        if (DaysInFirstWeek >= THURSDAY)
            WeekNumber = WeekNumber + 1;
     
        // If week number is larger than week 52
        // (and the year doesn't either start or end on a thursday)
        // then the correct week number is 1.
        if (WeekNumber > 52 && !ThursdayFlag)
            WeekNumber = 1;
     
        // If week number is still 0, it means that we are trying
        // to evaluate the week number for a week that belongs
        // in the previous year(since that week has 3 days or
        // less in our date's year).
        // We therefore make a recursive call using
        // the last day of the previous year.
        if (WeekNumber == 0)
            WeekNumber = WeekNumber_Entire4DayWeekRule(
                 new DateTime(date.Year - 1, DEC, LASTDAYOFDEC));
        return WeekNumber;
    }
    Pas de questions techniques par MP

  5. #5
    Membre expert Avatar de Amara
    Profil pro
    Inscrit en
    Juillet 2004
    Messages
    2 688
    Détails du profil
    Informations personnelles :
    Localisation : France, Sarthe (Pays de la Loire)

    Informations forums :
    Inscription : Juillet 2004
    Messages : 2 688
    Points : 3 115
    Points
    3 115
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    CultureInfo ci = new CultureInfo( "fr-FR" );
    int semaine = ci.Calendar.GetWeekOfYear( Calendar1.SelectedDates[0],
     CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday );
    Ce code a l'air de mieux marcher...
    Pas de questions techniques par MP, le forum est là pour ça et est plus efficace.

    Orthographe : une connexion (avec un x), un langage (sans u), une requête (un seul t), 'une quote' (avec qu), une syntaxe (sans h)

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Comment convertir d'une chaîne en Date
    Par the watcher dans le forum Collection et Stream
    Réponses: 6
    Dernier message: 16/08/2010, 12h21
  2. Comment mettre à jour une date ?
    Par Hokagge dans le forum MFC
    Réponses: 6
    Dernier message: 22/03/2006, 12h30
  3. Réponses: 10
    Dernier message: 09/01/2006, 18h39
  4. Comment vérifier qu'une date est nulle
    Par stressy dans le forum Access
    Réponses: 7
    Dernier message: 09/12/2005, 15h41

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo