我需要通过给出int year和int month来开始和结束日期的周列表,
示例结果,
第1周= 2012年7月1日至2012年7月1日
第2周= 2012年7月2日至2012年7月8日
第3周= 2012年7月9日至2012年7月15日
第4周= 2012年7月16日至2012年7月22日
第5周= 2012年7月23日至2012年7月29日
第6周= 2012年7月30日至2012年7月31日
答案 0 :(得分:6)
这样的事情应该有效:
// using System.Globalization;
var calendar = CultureInfo.CurrentCulture.Calendar;
var firstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
var weekPeriods =
Enumerable.Range(1, calendar.GetDaysInMonth(year, month))
.Select(d =>
{
var date = new DateTime(year, month, d);
var weekNumInYear = calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, firstDayOfWeek);
return new { date, weekNumInYear };
})
.GroupBy(x => x.weekNumInYear)
.Select(x => new { DateFrom = x.First().date, To = x.Last().date })
.ToList();
当然,您可以更改Culture
(此处我使用了CurrentCulture
)。
答案 1 :(得分:2)
检查一下并根据需要进行编辑
// Get the weeks in a month
DateTime date = DateTime.Today;
// first generate all dates in the month of 'date'
var dates = Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month)).Select(n => new DateTime(date.Year, date.Month, n));
// then filter the only the start of weeks
var weekends = (from d in dates
where d.DayOfWeek == DayOfWeek.Monday
select d).ToList();
foreach (var d in weekends)
{
Console.WriteLine(d);
}
Console.Write(weekends);
Console.ReadLine();
希望对你有所帮助。
您还可以查看其他内容HERE