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

后端 未结 6 864
[愿得一人]
[愿得一人] 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:43

    Here's an extension method we are using.

    public static class DateTimeExtensions
    {
        public static DateTime GetLastFridayInMonth(this DateTime date)
        {
            var firstDayOfNextMonth = new DateTime(date.Year, date.Month, 1).AddMonths(1);
            int vector = (((int)firstDayOfNextMonth.DayOfWeek + 1) % 7) + 1;
            return firstDayOfNextMonth.AddDays(-vector);
        }
    }
    

    Below is the MbUnit test case

    [TestFixture]
    public class DateTimeExtensionTests
    {
      [Test]
      [Row(1, 2011, "2011-01-28")]
      [Row(2, 2011, "2011-02-25")]
      ...
      [Row(11, 2011, "2011-11-25")]
      [Row(12, 2011, "2011-12-30")]
      [Row(1, 2012, "2012-01-27")]
      [Row(2, 2012, "2012-02-24")]
      ...
      [Row(11, 2012, "2012-11-30")]
      [Row(12, 2012, "2012-12-28")]
    
      public void Test_GetLastFridayInMonth(int month, int year, string expectedDate)
      {
        var date = new DateTime(year, month, 1);
        var expectedValue = DateTime.Parse(expectedDate);
    
        while (date.Month == month)
        {
          var result = date.GetLastFridayInMonth();
          Assert.AreEqual(expectedValue, result);
          date = date.AddDays(1);
        }
      }
    }
    

提交回复
热议问题