Tuesday, November 24, 2009

Find next specific day of week

It’s not cutting edge but it’s something I forget about every 6 months and have to look up or figure out again.  So here it is.  Also I’m not convinced that it is the best way so if anyone knows a better one feel free to let me know.

ok I have written a battery of tests changing both days around and this is the real deal.

public DateTime getNextSpecificDay(DateTime d1, DayOfWeek day)
        {
            var diff = day - d1.DayOfWeek;
            if(diff <= 0)
            {
                diff = diff + 7;
            }
            return d1.AddDays(diff);
        }

 

this will find the next sunday.  if you pass in a sunday it will find the next one not the current one.