John Porter
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!
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!
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.Sat urday - 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.T oString("d ddd") + ", " + Saturday.ToString("MMMM dd, yyyy"));
}
private System.DateTime GetNextDay(System.DateTime dt, DayOfWeek day)
{
return dt.AddDays(day - dt.DayOfWeek);
}
DateTime GetNextSaturday(DateTime time)
{
return time.AddDays(DayOfWeek.Sat
}
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
MessageBox.Show(Saturday.T
}
private System.DateTime GetNextDay(System.DateTime
{
return dt.AddDays(day - dt.DayOfWeek);
}
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;
}
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;
}