我想在选择月份时在下拉列表中填充周数 当我选择
January
然后它将仅显示从星期一开始的周数
1st week:
Monday(02/01/2012)
2nd week:
Monday(09/01/2012)
3rd week:
Monday(16/01/2012)
4th week:
Monday(23/01/2012)
5th week:
Monday(30/01/2012)
答案 0 :(得分:2)
所以听起来你需要在本周的周一找到第一个,然后继续增加一周,直到你不再在同一个月:
using System;
using System.Collections.Generic;
class Test
{
static void Main(string[] args)
{
foreach (DateTime date in GetMondays(2012, 1))
{
Console.WriteLine(date);
}
}
static IEnumerable<DateTime> GetMondays(int year, int month)
{
DateTime startOfMonth = new DateTime(year, month, 1);
// Get to the first Monday
int daysToMonday = DayOfWeek.Monday - startOfMonth.DayOfWeek;
// Now make sure it's non-negative...
int daysToNextMonday = (daysToMonday + 7) % 7;
// Add it to the start of the month to get to the first Monday
DateTime firstMonday = startOfMonth.AddDays(daysToNextMonday);
// Now yield and iterate until we're done
for (DateTime date = firstMonday;
date.Month == month;
date = date.AddDays(7))
{
yield return date;
}
}
}
(您可以将日期添加到列表中,如果您愿意,则返回该日期......实际上并没有太大区别。)
答案 1 :(得分:0)
简单地解析从月份的开始日期到月份的结束日期的所有内容。
每天检查DayOfWeek
并打印结果