Поиск каждой пятницы от даты начала до конца года - PullRequest
2 голосов
/ 20 августа 2011

Итак, я вернулся с еще одним озадачивающим вопросом DateTime.

В C # как бы я возвращал (день) для каждой пятницы с начальной даты (DateTime.Now) до конца текущего года?

Так, например, сегодня, в пятницу 19-го, он вернется, 26, 2, 9, 16, 23, 30, 7 и т. Д.

Ответы [ 6 ]

8 голосов
/ 20 августа 2011

Это работает?

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 голосов
/ 20 августа 2011
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);
1 голос
/ 20 августа 2011

Это будет делать то, что вы хотите.

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;
}
0 голосов
/ 15 июня 2018

Я эксперт по vb.net .. но нет никаких отличий ..

Я написал код ниже в page_load веб-форме asp.net ...

  1. создать asp.net приложение
  2. добавить к нему веб-форму
  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 & "<br />")
                d = gc.AddDays(d, 7)
                i += 7
            Else
                d = gc.AddDays(d, 1)
                i += 1
            End If
        End While
    End Sub
    
0 голосов
/ 22 августа 2011

Вы можете использовать CalendarPeriodCollector библиотеки Time Period для .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
0 голосов
/ 20 августа 2011

Мой ответ ...

    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();
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...