Cronos icon indicating copy to clipboard operation
Cronos copied to clipboard

GetPreviousOccurrence

Open andr3marra opened this issue 1 year ago • 3 comments

Hello, I want to know how I can get a Previous Ocurrence from a Cron expression. I tried reading the source code but couldn't understand how it works. The only i could get it is expression.GetOccurence(DateTime.MinValue.ToUniversalTime(), fromUTC).Reverse().Skip(1).First(). Is there a better way to do this? Does this request makes sense to add as a feature? If so what can I read to better my understanding of the algorithm used so I can implement it myself. Ty in advance

andr3marra avatar Mar 15 '24 21:03 andr3marra

How is this problem currently being solved?

zhangguichang avatar Aug 09 '24 04:08 zhangguichang

I've recently created a library called Occurify.TimeZones that can be used to do just this. It uses Cronos under the hood and is also licensed under The MIT License (MIT):

using Occurify.TimeZones;

var cronTimeline = TimeZoneInstants.FromCron("0 * * * *");
var previousOccurrence = cronTimeline.GetPreviousUtcInstant(DateTime.UtcNow);

TimeZoneInstants.FromCron gives you a ITimeline you can traverse in both directions.

Implementation The implementation is simular to what you suggest in your comment. It will take the difference between the very first instant and the second instant to create a search window duration. Using that duration, it will simply loop back and get all instances within that duration relative to where the search starts, then take the last instant of that. Since cron intervals are roughly the same, usually it only takes 1 or 2 iterations to find what we need. Source: here.

Also: be careful with using CronExpression.GetOccurrences using DateTime.MinValue. Depending on your cron expression, it might not work. For more information, see the following issue I created: GetOccurrences doesn't work for new DateTime(0, DateTimeKind.Utc) #76.

DevJasperNL avatar Mar 15 '25 16:03 DevJasperNL

Thanks for your help. I'll keep a look in Occurify and try it as soon as i can

andr3marra avatar Mar 30 '25 00:03 andr3marra