Get saturday date value from a selected week using a month calendar
I am kinda stuck about this problem. How can I get the month calendar saturday values when i selected a specific date.
For example: i se开发者_如何学运维lected February 14 on the month calendar. After selecting it there will be a prompt which contains Saturday "February 19, 2011" or i selected February 24, The prompt will display "February 26 2011".
// 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;
}
}
}
DateTime add = DateTime.Now; //From popup box
int add = (((int)selected.DayOfWeek) + 1;
if(add != 7) {
selected = selected.AddDays(add);
}
精彩评论