简体   繁体   中英

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 selected 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM