imagine that i have a property called NextSend representing DateTime Value
4/11/2011 10:30:00 AM - Monday
lets say that I have a schedule which must be sent every week for specific day (Monday) in this case, so in order to figure out the next weekly schedule I ended up with the solution where I have to check every next date’s day till the DayOfWeek Matches the specific day in the schedule
4/17/2011 10:30:00 AM - Monday
Is there any other best way to overcome checking each next day date’s day name?
here is my mentioned logic:
int nowYear = DateTime.Now.Year;
int nowMonth = DateTime.Now.Month;
int nowDay = DateTime.Now.Day;
int scheduleHour = this.Schedule.Time.Value.Hour;
int scheduleMinute = this.Schedule.Time.Value.Minute;
int scheduleSecond = this.Schedule.Time.Value.Second;
int scheduleDay = -1;
if(this.Schedule.Day.HasValue)
scheduleDay= this.Schedule.Day.Value;
switch (type)
{
case Schedule.ScheduleType.Weekly:
bool founded = false;
while (!founded)
{
//Check if last day of the current month
if (DateTime.DaysInMonth(nowYear, nowMonth) == nowDay)
{
//last day at this year, then move to next year
if (nowMonth == 12)
{
nowYear++;
nowMonth = 1;
nowDay = 1;
}
//its the end of a month then Move to next month
else
{
nowMonth++;
nowDay = 1;
}
}
//Get new proposed date
newNextSend = new DateTime(nowYear, nowMonth, nowDay, scheduleHour, scheduleMinute, scheduleSecond);
//Check if Next week schedule founded with specific day name
if (newNextSend.DayOfWeek ==
(DayOfWeek)Enum.Parse(typeof(DayOfWeek), Schedule.daysCalendar[scheduleDay - 1]))
{
founded = true;
}
else
nowDay++;
}
break;
}
As all the other folks have said as well: AddDays(7) will ensure the weekly schedule runs as required. But if you’re looking for a way to figure out the next occurrence of a specific weekday, then you can do something like this:
Then a call like this
will return the first occurrence of Wednesday. After which the weekly schedule carries on running. If you need the first occurrence of “Wednesday” as of next week, just pass
to the “startDate” parameter of the above method.