查找每个星期五从开始日期到年底

所以我又回到了另一个令人困惑的DateTime问题。

在C#中,我如何从开始日期( DateTime.Now )返回每周五的(日)直到当年年底?

因此,例如,今天是19日星期五,它将返回,26,2,9,16,23,30,7等。

这有用吗?

 static IEnumerable 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); 

这可以做你想要的。

 IList getFridaysForYearFromPoint(DateTime startDate) { DateTime currentFriday = startDate; List results = new List(); //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 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(); } 

您可以使用.NET时间段库的CalendarPeriodCollector

 // ---------------------------------------------------------------------- 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 

我是vb.net的专家..但没有什么不同..

我在asp.net web表单的page_load中编写了下面的代码…

  1. 制作一个asp.net应用程序
  2. 添加Web表单
  3. page_load写下面的代码

     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim gc As New System.Globalization.GregorianCalendar Dim d As New DateTime(gc.GetYear(DateTime.Now), 1, 1) Dim i As Int16 = 1 While i <= gc.GetDaysInYear(gc.GetYear(DateTime.Now)) If gc.GetDayOfWeek(d) = DayOfWeek.Friday Then Response.Write(d & "
    ") d = gc.AddDays(d, 7) i += 7 Else d = gc.AddDays(d, 1) i += 1 End If End While End Sub