所以我回来了另一个莫名其妙的DateTime问题。查找每个星期五从开始日期到年底
在C#中,我将如何从开始日期(DateTime.Now
)开始每个星期五返回(当天)直到本年结束?
因此,举例来说,今天是周五的19日,它将返回,26,2,9,16,23,30,7等
所以我回来了另一个莫名其妙的DateTime问题。查找每个星期五从开始日期到年底
在C#中,我将如何从开始日期(DateTime.Now
)开始每个星期五返回(当天)直到本年结束?
因此,举例来说,今天是周五的19日,它将返回,26,2,9,16,23,30,7等
这将做你想要的。
IList<int> getFridaysForYearFromPoint(DateTime startDate)
{
DateTime currentFriday = startDate;
List<int> results = new List<int>();
//Find the nearest Friday forward of the start date
while(currentFriday.DayOfWeek != DayOfWeek.Friday)
{
currentFriday = currentFriday.AddDays(1);
}
//FIND ALL THE FRIDAYS!
int currentYear = startDate.Year;
while (currentFriday.Year == currentYear)
{
results.Add(startDate.Day);
currentFriday = currentFriday.AddDays(7);
}
return results;
}
这工作?
static IEnumerable<DateTime> GetFridays(DateTime startdate, DateTime enddate)
{
// step forward to the first friday
while (startdate.DayOfWeek != DayOfWeek.Friday)
startdate = startdate.AddDays(1);
while (startdate < enddate)
{
yield return startdate;
startdate = startdate.AddDays(7);
}
}
var start = DateTime.Today;
var startDay = ((int) start.DayOfWeek);
var nextFriday = startDay<6 //5 if today is friday and you don't want to count it
? start.AddDays(5 - startDay) //friday this week
: start.AddDays(12 - startDay); //friday next week
var remainingFridays = Enumerable.Range(0,53)
.Select(i => nextFriday.AddDays(7 * i))
.TakeWhile(d => d.Year == start.Year);
我的答案...
static void Main(string[] args)
{
DateTime begin = DateTime.Now;
DateTime end = DateTime.Now.AddDays(200);
while (begin <= end)
{
if (begin.DayOfWeek == DayOfWeek.Friday)
Console.WriteLine(begin.ToLongDateString());
begin = begin.AddDays(1);
}
Console.ReadKey();
}
可以使用CalendarPeriodCollector的Time Period Library for .NET的:
// ----------------------------------------------------------------------
public void FindRemainigYearFridaysSample()
{
// filter: only Fridays
CalendarPeriodCollectorFilter filter = new CalendarPeriodCollectorFilter();
filter.WeekDays.Add(DayOfWeek.Friday);
// the collecting period
CalendarTimeRange collectPeriod = new CalendarTimeRange(DateTime.Now, new Year().End.Date);
// collect all Fridays
CalendarPeriodCollector collector = new CalendarPeriodCollector(filter, collectPeriod);
collector.CollectDays();
// show the results
foreach (ITimePeriod period in collector.Periods)
{
Console.WriteLine("Friday: " + period);
}
} // FindRemainigYearFridaysSample
为起始日期周五或你需要弄清楚第一个星期五呢? – Mrchief
我需要弄清楚第一个星期五,因为当我检查时,这一天不会总是在星期五。 –