Calendar.GetWeekOfYear(DateTime, CalendarWeekRule, DayOfWeek) Метод

Определение

Возвращает неделю года, к которой относится дата в заданном значении DateTime.

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

Параметры

time
DateTime

Значение даты и времени.

rule
CalendarWeekRule

Значение перечисления, определяющее календарную неделю.

firstDayOfWeek
DayOfWeek

Значение перечисления, представляющее первый день недели.

Возвращаемое значение

Положительное целое число, представляющее неделю года, к которой относится дата в параметре time.

Исключения

Время, указанное в параметре time, наступает раньше момента времени, определенного свойством MinSupportedDateTime, или позже момента времени, определенного свойством MaxSupportedDateTime.

-или-

firstDayOfWeek не является допустимым значением DayOfWeek.

-или-

rule не является допустимым значением CalendarWeekRule.

Примеры

В следующем примере кода показано, как результат GetWeekOfYear зависит от используемых FirstDayOfWeekCalendarWeekRule и . Если указанная дата является последним днем года, GetWeekOfYear возвращает общее количество недель в этом году.

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

Комментарии

Этот метод можно использовать для определения количества недель в году, задав time значение последнего дня года.

Объект DateTimeFormatInfo для определенного языка и региональных параметров, использующий календарь, указанный DateTimeFormatInfo.Calendar свойством , включает следующие значения, относящиеся к языку rule и региональным параметрам, которые можно использовать для параметров и firstDayOfWeek :

  • Свойство DateTimeFormatInfo.FirstDayOfWeek содержит первый день недели по умолчанию, который можно использовать для firstDayOfWeek параметра .

  • Свойство DateTimeFormatInfo.CalendarWeekRule содержит правило календарной недели по умолчанию, которое можно использовать для rule параметра .

Примечание

Это не соответствует стандарту ISO 8601. Различия обсуждаются в записи блога в формате iso 8601 Week of Year в Майкрософт .NET. Начиная с .NET Core 3.0, ISOWeek.GetYear и ISOWeek.GetWeekOfYear решить эту проблему.

В следующем примере объект текущего языка и региональных DateTimeFormatInfo параметров используется для определения того, что 1 января 2011 года находится в первой неделе года в григорианском календаре.

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)

Для некоторых календарей вызов GetWeekOfYear метода вызывает ArgumentOutOfRangeException исключение для определенных сочетаний значений rule и , firstDayOfWeek даже если time больше даты, возвращаемой свойством этого календаря MinSupportedDateTime . В следующей таблице перечислены затронутые календари, конкретные rule значения и диапазон самых ранних поддерживаемых time значений. Конкретное минимальное DateTime значение зависит от значения firstDayOfWeek параметра.

Календарь Значение CalendarWeekRule Григорианская дата (М/дд/гггг) Дата в календаре (М/дд/гггг)
ChineseLunisolarCalendar FirstFullWeek С 19.02.1901 по 25.02.1901 С 1/1/1901 по 7.01.1901
ChineseLunisolarCalendar FirstFourDayWeek С 19.02.1901 по 22.02.1901 С 01.01.1901 по 04.01.1901
HebrewCalendar FirstDay 9/17/1583 1/01/5344
HebrewCalendar FirstFullWeek С 17.09.1583 по 23.09.1583 С 01.01.5344 по 07.01.5344
HebrewCalendar FirstFourDayWeek С 17.09.1583 по 20.09.1583 с 01.01.5344 по 04.01.5344
HijriCalendar FirstFullWeek с 18.07.0622 по 24.07.0622 С 1/01/0001 по 01/07/0001
HijriCalendar FirstFourDayWeek с 18.07.0622 по 21.07.0622 с 01.01.0001 по 01.04.0001
JapaneseLunisolarCalendar FirstFullWeek С 28.01.1960 по 03.02.1960 С 01.01.35 по 07.01.0035
JapaneseLunisolarCalendar FirstFourDayWeek С 28.01.1960 по 31.01.1960 с 01.01.0035 по 04.01.0035
JulianCalendar FirstFullWeek С 1/01/0001 по 01/05/0001 с 1/03/0001 по 01/07/0001
JulianCalendar FirstFourDayWeek с 1/01/0001 по 01/02/0001 С 1/03/0001 по 01/04/0001
KoreanLunisolarCalendar FirstFullWeek С 14.02.0918 по 20.02.0918 с 01.01.0918 по 01.07.0918
KoreanLunisolarCalendar FirstFourDayWeek С 14.02.0918 по 17.02.0918 с 01.01.0918 по 04.01.018
PersianCalendar FirstFullWeek с 21.03.0622 по 27.03.0622 С 1/01/0001 по 01/07/0001
PersianCalendar FirstFourDayWeek с 21.03.0622 по 24.03.0622 с 01.01.0001 по 01.04.0001
TaiwanLunisolarCalendar FirstFullWeek С 18.02.1912 по 24.02.1912 С 1/01/0001 по 01/07/0001
TaiwanLunisolarCalendar FirstFourDayWeek С 18.02.1912 по 21.02.1912 с 01.01.0001 по 01.04.0001
UmAlQuraCalendar FirstFullWeek С 30.04.1900 по 06.05.1900 с 01.01.1318 по 07.01.1318
UmAlQuraCalendar FirstFourDayWeek С 30.04.1900 по 03.05.1900 с 01.01.1318 по 04.01.1318

Применяется к

См. также раздел