我有两个日期时间选择器,名为dtpStartDate和dtpEndDate。当用户选择dtpStartDate和dtpEndDate的日期时,我希望获得这两个日期时间选择器值之间的所有工作日期。
例如: - 如果用户选择dtpStartDate为“30-01-2014”而dtpEndDate为“05-02-2014”输出结果应为
30-01-2014 //(Thursday)
31-01-2014 //(Friday)
03-02-2014 //(Monday)
04-02-2014 //(Tuesday)
05-02-2014 //(WednesDay)
(01-02-2014和02-02-2014不应属于输出,因为那些日子是假期。)
请有人给我一个完成该任务的正确代码。谢谢。
答案 0 :(得分:1)
你可以这样做:
var startDate= dtpStartDate.Date;
var endDate= dtpEndDate.Date;
List<DateTime> workingDays= new List<DateTime>();
for(DateTime counter= startDate; counter<= endDate; counter=counter.AddDays(1))
{
if(counter.DayOfWeek !=DayOfWeek.Saturday && counter.DayOfWeek!=DayOfWeek.Sunday)
workingDays.Add(counter);
}
// Here you can use the list of working days.
答案 1 :(得分:0)
我尝试过Linq的解决方案。它有效,但我不确定是否有更好的方法。
DateTime d1 = new DateTime(2014,1,30);
DateTime d2 = new DateTime(2014,2,5);
int totalDays = (int)(d2 - d1).TotalDays;
List<DateTime> dateStart = new List<DateTime>(){d1};
var result = dateStart.SelectMany(d => Enumerable.Range(0, totalDays)
.Select(days => d.AddDays(days))
.Where(x => x.DayOfWeek != DayOfWeek.Sunday &&
x.DayOfWeek != DayOfWeek.Saturday));