Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GetPreviousOccurrence #67

Open
andr3marra opened this issue Mar 15, 2024 · 2 comments
Open

GetPreviousOccurrence #67

andr3marra opened this issue Mar 15, 2024 · 2 comments

Comments

@andr3marra
Copy link

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

@zhangguichang
Copy link

How is this problem currently being solved?

@DevJasperNL
Copy link
Contributor

DevJasperNL commented Mar 15, 2025

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

3 participants