Click here to Skip to main content
15,887,903 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have got a doubt in Calendar control. I don't know how to select all the second week of Saturday in a year. I have to use Calendar control. Its forecolor should be in Red color. Should i use bool flag for selecting second week of Saturday?

C#
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {
        bool flag = false;
        if (e.Day.Date.DayOfWeek.ToString() == "Saturday")
        {
            flag = true;
            e.Cell.ForeColor = System.Drawing.Color.Red;
        }
        if(!flag)
        {
            
        }
        }
    }
Posted
Comments
What is happening with the current code?
[no name] 29-Jun-14 13:00pm    
it highlights all saturday every year...i need to highlight only the second saturday every year.
CHill60 29-Jun-14 12:50pm    
Do you mean that you want to highlight every other Saturday, or do you mean you only want to highlight the second Saturday each year?
[no name] 29-Jun-14 13:00pm    
yes..i have to highlight the second saturday each year.

1 solution

You need to replace your check for "Saturday" with a check for 2nd Saturday in a year...e.g.
C#
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
 {
     CalendarDay dateToCheck = e.Day;
     if(Is2ndSaturday(dateToCheck.Date))
     {
         e.Cell.BackColor = Color.Red;

     }

 }

Setting and checking flag is fairly pointless but if you wanted to speed things up you could skip the test each year once you've already highlighted the date for that year.

The function Is2ndSaturday below takes a fairly "brute force" approach. I start with January 1st for the year being displayed, checks to see if it (1st Jan) is already a Saturday and if not just increment a working date until it finds a Saturday. That will be the first Saturday, so once you've found it, just add 7 days to find the second Saturday.
Here I've just compared the date of the second Saturday to the input date and return a bool if they match. You could change it to return the date instead.
C#
private bool Is2ndSaturday(DateTime dtIn)
{
    // get the first day of the year for the current date
    DateTime dt1 = new DateTime(dtIn.Year, 1, 1);

    //Check to see if it's a saturday
    while (dt1.DayOfWeek != DayOfWeek.Saturday)
    {
        dt1.AddDays(1.0);
    }
    dt1.AddDays(7); //dt1 now contains the date of the 2nd saturday for this year

    //Check to see if the day we are working on is that 2nd saturday
    return (dtIn.CompareTo(dt1) == 0) ? true : false;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900