如何获得给定年份的周数

尝试编写一个正确的函数,该函数返回给定年份的周数,但没有成功。

我正在寻找的function示例:

int weeks = GetWeeksInYear ( 2012 ) 

应该返回52周//意味着2012年只有52周。

Ps:在一年中可以是52,53,54周,不确定51

请参阅Calendar.GetWeekOfYear方法

 public int GetWeeksInYear(int year) { DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo; DateTime date1 = new DateTime(year, 12, 31); Calendar cal = dfi.Calendar; return cal.GetWeekOfYear(date1, dfi.CalendarWeekRule, dfi.FirstDayOfWeek); } 

小心找出正确的CalendarWeekRule和FirstDayOfWeek,以获得与您的客户习惯的文化相匹配的日历。 (对于某些压光机,它可能会有所不同……)

当我将2018分配给其他方法的年份参数时,我遇到了问题。 我不知道是否有代码可以更快地工作,但我写了以下方法。

  //you can try like that int weeks = DateHelper.GetWeeksInGivenYear(2018); int weeks = DateHelper.GetWeeksInGivenYear(2020); // This presumes that weeks start with Monday. // Week 1 is the 1st week of the year with a Thursday in it. public static int GetIso8601WeekOfYear(this DateTime time) { // Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll // be the same week# as whatever Thursday, Friday or Saturday are, // and we always get those right DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time); if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday) { time = time.AddDays(3); } // Return the week of our adjusted day return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); } //gets given year last week no public static int GetWeeksInGivenYear(int year) { DateTime lastDate = new DateTime(year, 12, 31); int lastWeek = GetIso8601WeekOfYear(lastDate); while (lastWeek == 1) { lastDate = lastDate.AddDays(-1); lastWeek = GetIso8601WeekOfYear(lastDate); } return lastWeek; }