Get saturday date value from a selected week using a month calendar
Asked Answered
R

3

6

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".

enter image description here

Rid answered 14/2, 2011 at 1:33 Comment(0)
H
14
// 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;
      }
   }
 }
Honestly answered 14/2, 2011 at 1:40 Comment(0)
T
3
DateTime add = DateTime.Now; //From popup box
int add = (((int)selected.DayOfWeek) + 1;
if(add != 7) {
    selected = selected.AddDays(add);
}
Threlkeld answered 14/2, 2011 at 1:44 Comment(2)
@scrum is more efficient (+1) than my (@richard) answer. But I think mine is more maintainable.Honestly
@richard-schneider Thx, its almost always the correct move to take "maintainable" over "efficiency"Threlkeld
C
0
public DateTime DayInWeek(DateTime self, DayOfWeek dayOfWeek) 
{
        DateTime lRet = self;    
        int diff = (self.DayOfWeek - dayOfWeek) % 7;
        lRet = self.AddDays(-1 * diff).Date;
        return lRet; 
}

My solution assuming Sunday as first day of week

Cammiecammy answered 21/6, 2023 at 14:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.