我有一个表单接受'月'和'年'的输入,我写这里是为了询问我将如何获得所有“工作周”?
我指的是周一至周五的“工作周”
所以基本上我需要第1周到第4周,或者如果可用,包括第5周。
例如,如果我输入2013年1月:
week1 = January 1 to January 4
week2 = January 7 to January 11
week3 = January 14 to January 18
week4 = January 21 to January 25
week5 = January 28 to January 31
我怎样才能实现这一目标?谢谢你的帮助!任何建议或想法将不胜感激。谢谢伙伴们! :)
答案 0 :(得分:4)
您可以使用此Linq查询:
int month = 1;
int year = 2013;
var cal = System.Globalization.CultureInfo.CurrentCulture.Calendar;
IEnumerable<int> daysInMonth = Enumerable.Range(1, cal.GetDaysInMonth(year, month));
List<Tuple<int, DateTime, DateTime>> listOfWorkWeeks = daysInMonth
.Select(day => new DateTime(year, month, day))
.GroupBy(d => cal.GetWeekOfYear(d, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday))
.Select(g => Tuple.Create(g.Key, g.First(), g.Last(d => d.DayOfWeek != DayOfWeek.Saturday && d.DayOfWeek != DayOfWeek.Sunday)))
.ToList();
// Item1 = week in year, Item2 = first day, Item3 = last working day
int weekNum = 1;
foreach (var weekGroup in listOfWorkWeeks)
{
Console.WriteLine("Week{0} = {1} {2} to {1} {3}"
, weekNum++
, System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month)
, weekGroup.Item2.Day
, weekGroup.Item3.Day);
}
1月的输出:
Week1 = January 1 to January 4
Week2 = January 7 to January 11
Week3 = January 14 to January 18
Week4 = January 21 to January 25
Week5 = January 28 to January 31
和二月:
Week1 = February 1 to February 1
Week2 = February 4 to February 8
Week3 = February 11 to February 15
Week4 = February 18 to February 22
Week5 = February 25 to February 28
答案 1 :(得分:0)
查找月份和年份的第一个星期一。
int year = 2013;
int month = 1;
DateTime testDate = new DateTime(year,month,1);
while ( testDate.DayOfWeek != DayOfWeek.Monday )
{
testDate = testDate.AddDays(1);
}
然后每周迭代一次,直到你达到2013年的一年。
// Should have first monday now.
// Loop until the month changes
while ( testDate.Month == month)
{
var monday = testDate;
var friday = testDate.AddDays(4);
// You now have both dates. Do whatever you need to.
// here.
// Increment test date by a week
testDate = testDate.AddDays(7)
}
答案 2 :(得分:0)
在伪代码中:
while(day!= Monday)取下一个日期(+1天)
请查看this SO post(Jon Skeet回答!),了解一天是否是星期一。
添加4天以查找工作周结束
如果是在同一个月,那么你的工作周就会得到答案。
添加7天查找下周一
编辑以上查找所有完整工作周。
还可以找到其他周: