2011-08-20 99 views
2

所以我回來了另一個莫名其妙的DateTime問題。查找每個星期五從開始日期到年底

在C#中,我將如何從開始日期(DateTime.Now)開始每個星期五返回(當天)直到本年結束?

因此,舉例來說,今天是週五的19日,它將返回,26,2,9,16,23,30,7等

+0

爲起始日期週五或你需要弄清楚第一個星期五呢? – Mrchief

+0

我需要弄清楚第一個星期五,因爲當我檢查時,這一天不會總是在星期五。 –

回答

1

這將做你想要的。

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; 
} 
8

這工作?

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); 
    } 
} 
2
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); 
0

我的答案...

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(); 
    } 
0

可以使用CalendarPeriodCollectorTime 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 
相關問題