Compartilhar via


Calendar.GetWeekOfYear(DateTime, CalendarWeekRule, DayOfWeek) Método

Definição

Retorna a semana do ano que inclui a data no valor DateTime especificado.

public:
 virtual int GetWeekOfYear(DateTime time, System::Globalization::CalendarWeekRule rule, DayOfWeek firstDayOfWeek);
public virtual int GetWeekOfYear (DateTime time, System.Globalization.CalendarWeekRule rule, DayOfWeek firstDayOfWeek);
abstract member GetWeekOfYear : DateTime * System.Globalization.CalendarWeekRule * DayOfWeek -> int
override this.GetWeekOfYear : DateTime * System.Globalization.CalendarWeekRule * DayOfWeek -> int
Public Overridable Function GetWeekOfYear (time As DateTime, rule As CalendarWeekRule, firstDayOfWeek As DayOfWeek) As Integer

Parâmetros

time
DateTime

Um valor de data e hora.

rule
CalendarWeekRule

Um valor de enumeração que define uma semana de calendário.

firstDayOfWeek
DayOfWeek

Um valor de enumeração que representa o primeiro dia da semana.

Retornos

Um inteiro positivo que representa a semana do ano que inclui a data no parâmetro time.

Exceções

time é anterior a MinSupportedDateTime ou posterior a MaxSupportedDateTime.

- ou -

firstDayOfWeek não é um valor DayOfWeek válido.

- ou -

rule não é um valor CalendarWeekRule válido.

Exemplos

O exemplo de código a seguir mostra como o resultado de GetWeekOfYear varia dependendo do FirstDayOfWeek e do CalendarWeekRule usado. Se a data especificada for o último dia do ano, GetWeekOfYear retornará o número total de semanas nesse ano.

using namespace System;
using namespace System::Globalization;
int main()
{
   
   // Gets the Calendar instance associated with a CultureInfo.
   CultureInfo^ myCI = gcnew CultureInfo( "en-US" );
   Calendar^ myCal = myCI->Calendar;
   
   // Gets the DTFI properties required by GetWeekOfYear.
   CalendarWeekRule myCWR = myCI->DateTimeFormat->CalendarWeekRule;
   DayOfWeek myFirstDOW = myCI->DateTimeFormat->FirstDayOfWeek;
   
   // Displays the number of the current week relative to the beginning of the year.
   Console::WriteLine( "The CalendarWeekRule used for the en-US culture is {0}.", myCWR );
   Console::WriteLine( "The FirstDayOfWeek used for the en-US culture is {0}.", myFirstDOW );
   Console::WriteLine( "Therefore, the current week is Week {0} of the current year.", myCal->GetWeekOfYear( DateTime::Now, myCWR, myFirstDOW ) );
   
   // Displays the total number of weeks in the current year.
   DateTime LastDay = System::DateTime( DateTime::Now.Year, 12, 31 );
   Console::WriteLine( "There are {0} weeks in the current year ( {1}).", myCal->GetWeekOfYear( LastDay, myCWR, myFirstDOW ), LastDay.Year );
}

/*
This code produces the following output.  Results vary depending on the system date.

The CalendarWeekRule used for the en-US culture is FirstDay.
The FirstDayOfWeek used for the en-US culture is Sunday.
Therefore, the current week is Week 1 of the current year.
There are 53 weeks in the current year (2001).
*/
using System;
using System.Globalization;

public class SamplesCalendar  {

   public static void Main()  {

      // Gets the Calendar instance associated with a CultureInfo.
      CultureInfo myCI = new CultureInfo("en-US");
      Calendar myCal = myCI.Calendar;

      // Gets the DTFI properties required by GetWeekOfYear.
      CalendarWeekRule myCWR = myCI.DateTimeFormat.CalendarWeekRule;
      DayOfWeek myFirstDOW = myCI.DateTimeFormat.FirstDayOfWeek;

      // Displays the number of the current week relative to the beginning of the year.
      Console.WriteLine( "The CalendarWeekRule used for the en-US culture is {0}.", myCWR );
      Console.WriteLine( "The FirstDayOfWeek used for the en-US culture is {0}.", myFirstDOW );
      Console.WriteLine( "Therefore, the current week is Week {0} of the current year.", myCal.GetWeekOfYear( DateTime.Now, myCWR, myFirstDOW ));

      // Displays the total number of weeks in the current year.
      DateTime LastDay = new System.DateTime( DateTime.Now.Year, 12, 31 );
      Console.WriteLine( "There are {0} weeks in the current year ({1}).", myCal.GetWeekOfYear( LastDay, myCWR, myFirstDOW ), LastDay.Year );
   }
}

/*
This code produces the following output.  Results vary depending on the system date.

The CalendarWeekRule used for the en-US culture is FirstDay.
The FirstDayOfWeek used for the en-US culture is Sunday.
Therefore, the current week is Week 1 of the current year.
There are 53 weeks in the current year (2001).

*/
Imports System.Globalization

Public Class SamplesCalendar

   Public Shared Sub Main()
      
      ' Gets the Calendar instance associated with a CultureInfo.
      Dim myCI As New CultureInfo("en-US")
      Dim myCal As Calendar = myCI.Calendar
      
      ' Gets the DTFI properties required by GetWeekOfYear.
      Dim myCWR As CalendarWeekRule = myCI.DateTimeFormat.CalendarWeekRule
      Dim myFirstDOW As DayOfWeek = myCI.DateTimeFormat.FirstDayOfWeek
      
      ' Displays the number of the current week relative to the beginning of the year.
      Console.WriteLine("The CalendarWeekRule used for the en-US culture is {0}.", myCWR)
      Console.WriteLine("The FirstDayOfWeek used for the en-US culture is {0}.", myFirstDOW)
      Console.WriteLine("Therefore, the current week is Week {0} of the current year.", myCal.GetWeekOfYear(DateTime.Now, myCWR, myFirstDOW))
      
      ' Displays the total number of weeks in the current year.
      Dim LastDay = New System.DateTime(DateTime.Now.Year, 12, 31)
      Console.WriteLine("There are {0} weeks in the current year ({1}).", myCal.GetWeekOfYear(LastDay, myCWR, myFirstDOW), LastDay.Year)
   End Sub
End Class


'This code produces the following output.  Results vary depending on the system date.
'
'The CalendarWeekRule used for the en-US culture is FirstDay.
'The FirstDayOfWeek used for the en-US culture is Sunday.
'Therefore, the current week is Week 1 of the current year.
'There are 53 weeks in the current year (2001).

Comentários

Esse método pode ser usado para determinar o número de semanas no ano definindo time para o último dia do ano.

O DateTimeFormatInfo objeto para uma cultura específica que usa o calendário indicado pela DateTimeFormatInfo.Calendar propriedade inclui os seguintes valores específicos de cultura que podem ser usados para os rule parâmetros e firstDayOfWeek :

Observação

Isso não é mapeado exatamente para ISO 8601. As diferenças são discutidas no formato iso 8601 Week of Year da entrada de blog no Microsoft .NET. Começando com o .NET Core 3.0 ISOWeek.GetYear e ISOWeek.GetWeekOfYear resolva esse problema.

O exemplo a seguir usa o objeto da DateTimeFormatInfo cultura atual para determinar que 1º de janeiro de 2011 está na primeira semana do ano no calendário gregoriano.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
      DateTime date1 = new DateTime(2011, 1, 1);
      Calendar cal = dfi.Calendar;

      Console.WriteLine("{0:d}: Week {1} ({2})", date1,
                        cal.GetWeekOfYear(date1, dfi.CalendarWeekRule,
                                          dfi.FirstDayOfWeek),
                        cal.ToString().Substring(cal.ToString().LastIndexOf(".") + 1));
   }
}
// The example displays the following output:
//       1/1/2011: Week 1 (GregorianCalendar)
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim dfi As DateTimeFormatInfo = DateTimeFormatInfo.CurrentInfo
      Dim date1 As Date = #1/1/2011#
      Dim cal As Calendar = dfi.Calendar
      
      Console.WriteLine("{0:d}: Week {1} ({2})", date1, 
                        cal.GetWeekOfYear(date1, dfi.CalendarWeekRule, 
                                          dfi.FirstDayOfWeek),
                        cal.ToString().Substring(cal.ToString().LastIndexOf(".") + 1))       
   End Sub
End Module
' The example displays the following output:
'       1/1/2011: Week 1 (GregorianCalendar)

Para alguns calendários, uma chamada para o GetWeekOfYear método lança um ArgumentOutOfRangeException para combinações específicas de rule valores e firstDayOfWeek , mesmo que time seja maior que a data retornada pela propriedade desse MinSupportedDateTime calendário. A tabela a seguir lista os calendários afetados, os valores específicos rule e o intervalo dos primeiros valores com time suporte. O valor mínimo DateTime específico depende do valor do firstDayOfWeek parâmetro .

Calendário Valor CalendarWeekRule Data gregoriana (M/dd/yyyy) Data no calendário (M/dd/yyyy)
ChineseLunisolarCalendar FirstFullWeek 19/02/1901 a 25/02/1901 1/1/1901 a 7/1/1901
ChineseLunisolarCalendar FirstFourDayWeek 19/02/1901 a 22/02/1901 1/01/1901 a 04/1/1901
HebrewCalendar FirstDay 9/17/1583 1/01/5344
HebrewCalendar FirstFullWeek 17/09/1583 a 23/09/1583 1/01/5344 a 07/1/5344
HebrewCalendar FirstFourDayWeek 17/09/1583 a 20/09/1583 1/01/5344 a 04/1/5344
HijriCalendar FirstFullWeek 18/07/0622 a 24/07/0622 1/01/0001 a 07/01/0001
HijriCalendar FirstFourDayWeek 18/07/0622 a 21/07/0622 1/01/0001 a 04/01/0001
JapaneseLunisolarCalendar FirstFullWeek 28/1/1960 a 03/02/1960 1/01/35 a 07/01/0035
JapaneseLunisolarCalendar FirstFourDayWeek 28/1/1960 a 31/1/1960 1/01/0035 a 04/01/0035
JulianCalendar FirstFullWeek 1/01/0001 a 05/01/0001 03/01/0001 a 07/01/0001
JulianCalendar FirstFourDayWeek 1/01/0001 a 02/01/0001 03/01/0001 a 04/01/0001
KoreanLunisolarCalendar FirstFullWeek 14/02/0918 a 20/02/0918 1/01/0918 a 07/01/0918
KoreanLunisolarCalendar FirstFourDayWeek 14/02/0918 a 17/02/0918 1/01/0918 a 04/01/0918
PersianCalendar FirstFullWeek 21/03/0622 a 27/03/0622 1/01/0001 a 07/01/0001
PersianCalendar FirstFourDayWeek 21/03/0622 a 24/03/0622 1/01/0001 a 04/01/0001
TaiwanLunisolarCalendar FirstFullWeek 18/02/1912 a 24/02/1912 1/01/0001 a 07/01/0001
TaiwanLunisolarCalendar FirstFourDayWeek 18/02/1912 a 21/02/1912 1/01/0001 a 04/01/0001
UmAlQuraCalendar FirstFullWeek 30/04/1900 a 06/05/1900 1/01/1318 a 07/1/1318
UmAlQuraCalendar FirstFourDayWeek 30/04/1900 a 03/05/1900 1/01/1318 a 04/1/1318

Aplica-se a

Confira também