我想计算一个月内的周数.
2014年1月的第一周从第一个星期一开始是第6周.所以,1月有4个星期.从第一个星期一开始,2014年3月的第一周是第3周.所以,三月有5个星期.
我想知道一个月内有多少个星期从第一个星期一算起,而不是第一天.
我该怎么做呢?
我有这个代码,但它用于获取特定日期的月份周数.
public int GetWeekNumberOfMonth(DateTime date)
{
date = date.Date;
DateTime firstMonthDay = new DateTime(date.Year, date.Month, 1);
DateTime firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
if (firstMonthMonday > date)
{
firstMonthDay = firstMonthDay.AddMonths(-1);
firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
}
return (date - firstMonthMonday).Days / 7 + 1;
}
Run Code Online (Sandbox Code Playgroud)
Cyr*_*ral 16
试试这个:
获取当月的天数,找到第一天.对于该月中的每一天,查看该日是否为星期一,如果是,则递增该值.
public static int MondaysInMonth(DateTime thisMonth)
{
int mondays = 0;
int month = thisMonth.Month;
int year = thisMonth.Year;
int daysThisMonth = DateTime.DaysInMonth(year, month);
DateTime beginingOfThisMonth = new DateTime(year, month, 1);
for (int i = 0; i < daysThisMonth; i++)
if (beginingOfThisMonth.AddDays(i).DayOfWeek == DayOfWeek.Monday)
mondays++;
return mondays;
}
Run Code Online (Sandbox Code Playgroud)
您可以像当前日期一样使用它:
Console.WriteLine(MondaysInMonth(DateTime.Now));
Run Code Online (Sandbox Code Playgroud)
产量: 4
或者您选择的任何月份:
Console.WriteLine(MondaysInMonth(new DateTime(year, month, 1)))
Run Code Online (Sandbox Code Playgroud)