views:

146

answers:

0

I ran into this date and time constraint problem earlier this week, and haven't really found any good approach for an algorithm. Each idea I get grinds to a halt with something like what if this is a leap year? or what if this is run on the night when we change to/from DST


Input: A crontab expression (wikipedia on CRON format,Cron). For example:

0 */5 2,14 * * *

Meaning Every five minutes when the hour is 2 or 14

30 5 */2 1 * * */2

Meaning 5:30 past every even hour on the first of each month, every even year.


Output: The last time this expression was true. If run at 11:00 AM on november first, 2009, the output should be:

2009-11-01 02:55:00

for the first example and

2008-11-01 10:05:30

for the second.


Some notes:

There seems to be a couple of variations of the cron expression format: Some include seconds, some include year. The general problem should be about the same.

Feel free to apply sensible constraints; It's for example perfectly ok to don't handle years before 1970.

My current gut-feeling is that a depth-first search from year all the way down to second, backtracking when we run into invalid dates and times.

A brute-force approach could be to count backwards one day at a time, and evaluate the date part of the cron expression (there has only been about 15k days since 1970). When a valid day is found, do the same for the time part.

Answers doesn't have to contain code, I'm mostly after an algorithm outline like the ones above.