1
Vote

Error in Last specific day

description

Last Saturday of March 2008 is not the March 26...
The test functions is a bit lightweight...
 
Better Test fonction :
  [TestMethod]
  public void LastSpecificDayOfMonth( )
  {
     var dates = new DateTime[ ]  { new DateTime(2008,3,1), new DateTime(2008,3,15), new DateTime(2008,3,31)  };
     for (int day = 0 ; day < 7 ; day++)
     {
        var expected = new DateTime( 2008, 3, 31 - day );
        foreach (var date in dates)
        {
           var actual = date.Last( expected.DayOfWeek );
           Assert.AreEqual( expected, actual, string.Format("Date de test: {0}",date.ToShortDateString()) );
        }
     }
  }

comments

BillyDRyan wrote Jun 21, 2010 at 8:39 PM

this is old, but whatever.

Loic is correct; this is indeed a bug.

The method:
    /// <summary>
    /// Gets a DateTime representing the last specified day in the current month
    /// </summary>
    /// <param name="current">The current date</param>
    /// <param name="dayOfWeek">The current day of week</param>
    /// <returns></returns>
    public static DateTime Last(this DateTime current, DayOfWeek dayOfWeek)
    {
        DateTime last = current.Last();

        last = last.AddDays(Math.Abs(dayOfWeek - last.DayOfWeek) * -1);
        return last;
    }

The line:
   last = last.AddDays(Math.Abs(dayOfWeek - last.DayOfWeek) * -1);
for march of 2008, grabbing the last Saturday becomes
   last = last.AddDays(Math.Abs(6 - 1) * -1);
which is
   last = last.AddDays(-5)
so March (31-5) : March 26 which is a Wednesday. Instead of the proper March 29th.

Try changing it to something like:

last = last.AddDays((dayOfWeek > last.DayOfWeek) ? (-7 + dayOfWeek - last.DayOfWeek) : (dayOfWeek - last.DayOfWeek));

wrote Feb 13, 2013 at 9:28 PM