给定“日期名称”,如何获取给定两个日期之间的所有日期?
例如:Start_Date = 2011 年 1 月 1 日
End_Date = 2011 年1 月 20 日
日期名称=星期日
在这里,我们需要获取所有日期名称为“SUNDAY”的日期
例如:
Jan 02, 2011
Jan 09, 2011
Jan 16, 2011
我喜欢Enumerable.Range
用于这样的任务:
DateTime start = new DateTime(2011,1,1);
DateTime end = new DateTime(2011,1,20);
var datesThatAreSundays = Enumerable
.Range(start.DayOfYear, end.Subtract(start).Days + 1)
.Select(n => start.AddDays(n - start.DayOfYear))
.Where(d => d.DayOfWeek == DayOfWeek.Sunday);
像这样的东西怎么样
DateTime startDate = new DateTime(2011, 01, 01);
DateTime endDate = new DateTime(2011, 01, 20);
string dayName = "sunday";
List<DateTime> list = new List<DateTime>();
for (DateTime runDate = startDate; runDate <= endDate; runDate = runDate.AddDays(1))
{
if (runDate.DayOfWeek.ToString().ToLower() == dayName)
list.Add(runDate);
}
甚至使用Enum.TryParse
DateTime startDate = new DateTime(2011, 01, 01);
DateTime endDate = new DateTime(2011, 01, 20);
string dayName = "sunday";
DayOfWeek dow;
Enum.TryParse(dayName, true, out dow);
List<DateTime> list = new List<DateTime>();
for (DateTime runDate = startDate; runDate <= endDate; runDate = runDate.AddDays(1))
{
if (runDate.DayOfWeek == dow)
list.Add(runDate);
}
DateTime startDate = new DateTime(2011, 1, 1);
DateTime endDate = new DateTime(2011, 1, 20);
while (startDate < endDate)
{
if (startDate.DayOfWeek == DayOfWeek.Sunday)
{
// Do something
}
startDate = startDate.AddDays(1);
}
未经测试:
DateTime start = x;
DateTime end = y;
while (start.DayOfWeek != z)
start = start.AddDays(1);
while (start <= end)
{
//DoStuff
start = start.AddDays(7);
}
你可以试试这个
var firstDate = new DateTime(2011, 1, 1);
var lastDate = new DateTime(2011, 1, 20);
var result = (from el in Enumerable.Range(0, (lastDate - firstDate).Days)
let date = firstDate.AddDays(el)
where date.DayOfWeek == DayOfWeek.Sunday
select date).ToArray();