Link to home
Start Free TrialLog in
Avatar of John Porter
John PorterFlag for United States of America

asked on

Find Next Saturday Date from a known Date Value using C#

Hello Experts,

Does anyone know how to find the next Saturday date from a known date?

In other words, Say you have a date variable with a value of 10/1/2008
Is there a way to autimatically change the variable to the next Saturday date (10/4/2008 in this case)??

Thanks!
Avatar of p_davis
p_davis

you could make a method that takes a date and adds a day to it while the dates.dayofweek property isn't saturday.

ASKER CERTIFIED SOLUTION
Avatar of p_davis
p_davis

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
id just did this without an editor so it will need to be tested -- but the general idea should get you what you need.
Instead of looping, just use the DayOfWeek property directly to compute how many days to add:

    DateTime GetNextSaturday(DateTime time)
    {
        return time.AddDays(DayOfWeek.Saturday - time.DayOfWeek);
    }

Here is a generic helper function to get the next day of week that you specify:

    private void Button1_Click(object sender, System.EventArgs e)
    {
        System.DateTime Saturday = GetNextDay(System.DateTime.Today, DayOfWeek.Saturday);
        MessageBox.Show(Saturday.ToString("dddd") + ", " + Saturday.ToString("MMMM dd, yyyy"));
    }

    private System.DateTime GetNextDay(System.DateTime dt, DayOfWeek day)
    {
        return dt.AddDays(day - dt.DayOfWeek);
    }
Avatar of John Porter

ASKER

Thank you very much sir!

I modified your code a bit in case it was a Saturday sent in, I don't want the dat to increment
{
            //initialize startTime
            DateTime startTime = time.AddDays(0); // (0) instead of (1)
            while (startTime.DayOfWeek != DayOfWeek.Saturday)
            {

                startTime = startTime.AddDays(1);
            }
            return startTime;
        }