猿问

当星期从星期日开始时,从给定日期获取周数

当我一周的第一天是星期日时,如何从给定日期获得一年中正确的周数。


例如:


6 May 2018 - 12 May 2018 是第 18 周


13 May 2018 - 19 May 2018 是第 19 周


我正在尝试以下扩展方法,但无法达到预期的结果。它是第19周和第20周,我预计分别是第18周和第19周。


public static int GetWeekOfYear(this DateTime date)

{

    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(

      date, 

      CalendarWeekRule.FirstFourDayWeek, 

      DayOfWeek.Sunday);

}


胡子哥哥
浏览 266回答 2
2回答

慕容森

CalendarWeekRule Enumeration:定义确定一年中第一周的不同规则。以前你使用的是什么:CalendarWeekRule.FirstFourDayWeek需要替换为:CalendarWeekRule.FirstFullWeek因为:代码片段:public static void Main(){&nbsp; &nbsp; var week_test = Convert.ToDateTime("05/06/2018");&nbsp; &nbsp; var week_test2 = Convert.ToDateTime("05/13/2018");&nbsp; &nbsp; List<DateTime> weekList = new List<DateTime>();&nbsp; &nbsp; weekList.Add(week_test);&nbsp; &nbsp; weekList.Add(week_test2);&nbsp; &nbsp; CultureInfo ciCurr = CultureInfo.CurrentCulture;&nbsp; foreach(var week in weekList)&nbsp; {&nbsp; &nbsp; int weekNum = ciCurr.Calendar.GetWeekOfYear(week, CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday);&nbsp; &nbsp; Console.WriteLine(weekNum);&nbsp; }}输出:演示:dotNetFiddle

呼如林

您需要更改方法的参数CultureInfo.InvariantCulture.Calendar.GetWeekOfYear()CalendarWeekRule.FirstFourDayWeek -> CalendarWeekRule.FirstFullWeek根据文档为FirstFullWeek- 表示一年的第一周从该年的第一天或之后指定的一周的第一天的第一次出现开始。像这样public static int GetWeekOfYear(DateTime date){&nbsp; &nbsp; return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday);}
随时随地看视频慕课网APP
我要回答