How to get last Friday of month(s) using .NET

后端 未结 6 877
[愿得一人]
[愿得一人] 2020-12-07 02:03

I have a function that returns me only the fridays from a range of dates

public static List GetDates(DateTime startDate, int weeks)
{
    int         


        
6条回答
  •  被撕碎了的回忆
    2020-12-07 02:34

    Call the below function by sending the date as parameter, in which it extracts the month and year from the date parameter and returns the last Friday of that month

    public DateTime GetLastFridayOfMonth(DateTime dt)
    {
          DateTime dtMaxValue = DateTime.MaxValue;
          DateTime dtLastDayOfMonth = new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month));
    
          while (dtMaxValue == DateTime.MaxValue)
          {
               // Returns if the decremented day is the fisrt Friday from last(ie our last Friday)
               if (dtMaxValue == DateTime.MaxValue && dtLastDayOfMonth.DayOfWeek == DayOfWeek.Friday)
                   return dtLastDayOfMonth;
               // Decrements last day by one
               else
                  dtLastDayOfMonth = dtLastDayOfMonth.AddDays(-1.0);
          }
          return dtLastDayOfMonth;
    }
    

提交回复
热议问题