Pergunta

De acordo com o oficial (gregoriano) calendário , o número da semana para 29/12/2008 é 1, porque depois do último dia da semana 52 (ie 28/12) há três ou menos dias deixou no ano . Meio estranho, mas OK, regras são regras.

Assim, de acordo com este calendário, temos esses valores de limite para 2008/2009

  • 28/12 é semana 52
  • 29/12 é a semana 1
  • 1/1 é a semana 1
  • 8/1 é a semana 2

C # oferece uma classe GregorianCalendar, que tem uma função GetWeekOfYear(date, rule, firstDayOfWeek).

O rule parâmetro é uma enumeração com 3 valores possíveis: FirstDay, FirstFourWeekDay, FirstFullWeek. Pelo que eu entendi que eu deveria ir para a regra FirstFourWeekDay, mas eu tentei todos eles apenas no caso.

Os últimos informa parâmetros que dia da semana deve ser considerado o primeiro dia da semana, de acordo com o calendário que de segunda-feira para que segunda-feira que é.

Então, eu despediu-se um console app rápida e suja para testar esta:

using System;
using System.Globalization;

namespace CalendarTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var cal = new GregorianCalendar();
            var firstWeekDay = DayOfWeek.Monday;
            var twentyEighth = new DateTime(2008, 12, 28);
            var twentyNinth = new DateTime(2008, 12, 29);
            var firstJan = new DateTime(2009, 1, 1);
            var eightJan = new DateTime(2009, 1, 8);
            PrintWeekDays(cal, twentyEighth, firstWeekDay);
            PrintWeekDays(cal, twentyNinth, firstWeekDay);
            PrintWeekDays(cal, firstJan, firstWeekDay);
            PrintWeekDays(cal, eightJan, firstWeekDay);
            Console.ReadKey();
        }

        private static void PrintWeekDays(Calendar cal, DateTime dt, DayOfWeek firstWeekDay)
        {
            Console.WriteLine("Testing for " + dt.ToShortDateString());
            Console.WriteLine("--------------------------------------------");
            Console.Write(CalendarWeekRule.FirstDay.ToString() + "\t\t");
            Console.WriteLine(cal.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, firstWeekDay));
            Console.Write(CalendarWeekRule.FirstFourDayWeek.ToString() + "\t");
            Console.WriteLine(cal.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, firstWeekDay));
            Console.Write(CalendarWeekRule.FirstFullWeek.ToString() + "\t\t");
            Console.WriteLine(cal.GetWeekOfYear(dt, CalendarWeekRule.FirstFullWeek, firstWeekDay));
            Console.WriteLine("--------------------------------------------");
        }
    }
}

... e isso o que eu recebo

Testing for 28.12.2008
--------------------------------------------
FirstDay                52
FirstFourDayWeek        52
FirstFullWeek           51
--------------------------------------------
Testing for 29.12.2008
--------------------------------------------
FirstDay                53
FirstFourDayWeek        53
FirstFullWeek           52
--------------------------------------------
Testing for 01.01.2009
--------------------------------------------
FirstDay                1
FirstFourDayWeek        1
FirstFullWeek           52
--------------------------------------------
Testing for 08.01.2009
--------------------------------------------
FirstDay                2
FirstFourDayWeek        2
FirstFullWeek           1
--------------------------------------------

Então, como podemos ver, nenhuma das combinações acima partidas do calendário oficial (se você estiver com pressa, basta ver que 29/12 nunca fica semana # 1).

O que estou recebendo errado aqui? Talvez haja algo gritante que eu estou ausente? (É sexta-feira e as horas de trabalho final aqui na Bélgica, urso comigo;))

Edit: Talvez eu deva explicar: o que eu preciso é uma função que funciona para qualquer ano, retornando os mesmos resultados que o calendário gregoriano I ligada. soluções de forma que nenhum especiais para 2008.

Foi útil?

Solução

Este artigo observa mais a fundo o problema e possíveis soluções. O hub da questão é que a implementação do calendário .NET não parece implementar fielmente o padrão ISO

Outras dicas

@Conrad está correto. A implementação .NET de DateTime eo GregorianCalendar não implementam / siga a plena ISO 8601 spec. Dito isto, eles especificação é extremamente detalhada e não-trivial para implementar integralmente, pelo menos para o lado da análise das coisas.

Alguns mais informações está disponível nos seguintes sites:

Em termos simples:

Uma semana é identificado pelo seu número em um determinado ano e começa com uma segunda-feira. A primeira semana do ano é aquela que inclui a primeira quinta-feira, ou equivalentemente o que inclui 4 de janeiro.

Aqui está parte do uso de código I para lidar adequadamente ISO 8601 datas:

    #region FirstWeekOfYear
    /// <summary>
    /// Gets the first week of the year.
    /// </summary>
    /// <param name="year">The year to retrieve the first week of.</param>
    /// <returns>A <see cref="DateTime"/>representing the start of the first
    /// week of the year.</returns>
    /// <remarks>
    /// Week 01 of a year is per definition the first week that has the Thursday 
    /// in this year, which is equivalent to the week that contains the fourth
    /// day of January. In other words, the first week of a new year is the week
    /// that has the majority of its days in the new year. Week 01 might also 
    /// contain days from the previous year and the week before week 01 of a year
    /// is the last week (52 or 53) of the previous year even if it contains days 
    /// from the new year.
    /// A week starts with Monday (day 1) and ends with Sunday (day 7). 
    /// </remarks>
    private static DateTime FirstWeekOfYear(int year)
    {
        int dayNumber;

        // Get the date that represents the fourth day of January for the given year.
        DateTime date = new DateTime(year, 1, 4, 0, 0, 0, DateTimeKind.Utc);

        // A week starts with Monday (day 1) and ends with Sunday (day 7).
        // Since DayOfWeek.Sunday = 0, translate it to 7. All of the other values
        // are correct since DayOfWeek.Monday = 1.
        if (date.DayOfWeek == DayOfWeek.Sunday)
        {
            dayNumber = 7;
        }
        else
        {
            dayNumber = (int)date.DayOfWeek;
        }

        // Since the week starts with Monday, figure out what day that 
        // Monday falls on.
        return date.AddDays(1 - dayNumber);
    }

    #endregion

    #region GetIsoDate
    /// <summary>
    /// Gets the ISO date for the specified <see cref="DateTime"/>.
    /// </summary>
    /// <param name="date">The <see cref="DateTime"/> for which the ISO date
    /// should be calculated.</param>
    /// <returns>An <see cref="Int32"/> representing the ISO date.</returns>
    private static int GetIsoDate(DateTime date)
    {
        DateTime firstWeek;
        int year = date.Year;

        // If we are near the end of the year, then we need to calculate
        // what next year's first week should be.
        if (date >= new DateTime(year, 12, 29))
        {
            if (date == DateTime.MaxValue)
            {
                firstWeek = FirstWeekOfYear(year);
            }
            else
            {
                firstWeek = FirstWeekOfYear(year + 1);
            }

            // If the current date is less than next years first week, then
            // we are still in the last month of the current year; otherwise
            // change to next year.
            if (date < firstWeek)
            {
                firstWeek = FirstWeekOfYear(year);
            }
            else
            {
                year++;
            }
        }
        else
        {
            // We aren't near the end of the year, so make sure
            // we're not near the beginning.
            firstWeek = FirstWeekOfYear(year);

            // If the current date is less than the current years
            // first week, then we are in the last month of the
            // previous year.
            if (date < firstWeek)
            {
                if (date == DateTime.MinValue)
                {
                    firstWeek = FirstWeekOfYear(year);
                }
                else
                {
                    firstWeek = FirstWeekOfYear(--year);
                }
            }
        }

        // return the ISO date as a numeric value, so it makes it
        // easier to get the year and the week.
        return (year * 100) + ((date - firstWeek).Days / 7 + 1);
    }

    #endregion

    #region Week
    /// <summary>
    /// Gets the week component of the date represented by this instance.
    /// </summary>
    /// <value>The week, between 1 and 53.</value>
    public int Week
    {
        get
        {
            return this.isoDate % 100;
        }
    }
    #endregion

    #region Year
    /// <summary>
    /// Gets the year component of the date represented by this instance.
    /// </summary>
    /// <value>The year, between 1 and 9999.</value>
    public int Year
    {
        get
        {
            return this.isoDate / 100;
        }
    }
    #endregion

números Semana diferir de país para país e deve depender de sua localidade configurações / regionais, se eu não estou totalmente errado.

Edit: Wikipedia suporta minha vaga lembrança que estes números variam com base no país: http: // en.wikipedia.org/wiki/Week_number#Week_number

Eu esperaria um quadro respeitável de obedecer o país selecionado em seu tempo de execução local.

Na minha experiência, o comportamento demonstrado é o comportamento típico, referindo-se a semana final parcial na semana 53. Isso pode ser porque todos exposição significativa eu ??tive que números da semana tem sido relacionada a contabilidade final do ano civil para fins de relatório, eo IRS (ou agência de imposto de sua escolha) considera o ano civil para terminar em 31 de dezembro, não a última semana cheia do ano.

Eu sei que este é um post antigo, mas a qualquer momento maneira noda parece para obter o resultado correto ..

Como em torno do trabalho, você poderia dizer o número da semana é WeekNumber mod 52. Eu acredito que este iria trabalhar para os casos que você descreve.

Como alternativa, por que não usar FirstFourDayWeek mas acrescentar:

  if ( weekNumber > 52 )
    weekNumber = 1;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top