Search code examples
c#.netdatetime.net-4.0

Finding the next datetime based on a weekly, monthly schedule


I am trying to find the next scheduled date based on either a monthly or a weekly schedule.

e.g.

ScheduleMode: M or W for monthly or weekly
Monthly:
    1|15|29 will run on the 1st, 15th and 29th of every month

Weekly:
    1|3|5 will run every Monday, Wednesday and Friday

how do I go about figuring out what the next Datetime will be based on this data?

e.g. 12/16/2013 running weekly 1|3|5, next schedule will be 12/18/2013


Solution

  • You might try to use the Enum System.DayOfWeek. That happens to be the return type from DateTime.DayOfWeek, which you can use to find the weekday of the your starting date.

    From that, you should be able to find the next day(s) using DateTime.AddDays(x) or DateTime.AddMonths(X) (with some simple addition and subtraction to take the current weekday or date into account when finding x).

    Tip: If you have problems solving this, make sure you understand exactly what you need first. If necessary, write down your requirements in plain English before you try to code it. Once you've defined the problem clearly, solving it should actually not be too hard...