// This function will return the next saturday for a datetime
DateTime NextSaturday(DateTime now)
{
while (now.DayOfWeek != DayOfWeek.Saturday)
now = now.AddDays(1);
return now;
}
UPDATE
After almost 2 years I want to change this answer.
These days I would never create a "utility function" for a class
. I now always "extend" the class. The signature should now be DateTime.Next(DayOfWeek)
. See http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx for more details on extensions.
Also the logic is wrong. If now
is a Saturday then it would always return the current date. I think most callers would expect it return now
+ 7 days. So the first change is:
DateTime NextSaturday(DateTime now)
{
do {
now = now.AddDays(1);
} while (now.DayOfWeek != DayOfWeek.Saturday)
return now;
}
Then change the function to work with any day of the week:
DateTime Next(DateTime now, DayOfWeek nextDay)
{
do {
now = now.AddDays(1);
} while (now.DayOfWeek != nextDay)
return now;
}
Now "extend" the DateTime class to support Next(DayOfWeek)
namespace DateTime.Extensions
{
public static class DateTimeExtensions
{
public static DateTime Next(this DateTime now, DayOfWeek nextDay)
{
do {
now = now.AddDays(1);
} while (now.DayOfWeek != nextDay)
return now;
}
}
}