I need to find out the first occurrence of Date and time represented by given cron expression. Is there any java class, utility code which can help in getting data object from given cron expression ?
Asked
Active
Viewed 2.9k times
5 Answers
23
You can also leverage on spring's http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html for this
CronSequenceGenerator generator = new CronSequenceGenerator(cronExpression);
Date nextRunDate= generator.next(new Date());

lorraine batol
- 6,001
- 16
- 55
- 114
-
2Excellent answer! Simple, short and docs to boot. Perfect if using Spring as there's no need to add another third-party package. Thanks. – KWILLIAMS Sep 19 '18 at 16:17
-
1This is for default timezone. Use this `new CronSequenceGenerator(cronExpression, your_timezone);` for specific timezone. – Ram Sep 15 '20 at 06:43
21
You can check org.quartz.CronExpression It has a method named getNextValidTimeAfter which you can use.

saugata
- 2,823
- 1
- 27
- 39
8
If you're using Spring you could use:
CronTrigger trigger = new CronTrigger(cron);
TriggerContext context = new TriggerContext() {
public Date lastScheduledExecutionTime() {
return null;
}
public Date lastActualExecutionTime() {
return null;
}
public Date lastCompletionTime() {
return null;
}
};
return trigger.nextExecutionTime(context);

nMoncho
- 370
- 2
- 8
8
Here's an alternative similar to Quartz's CronExpression but without having to add a fully fledged scheduler to your project: cron-utils
You can get the date you need with the following:
//Get date for next execution
DateTime now = DateTime.now();
CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(QUARTZ);
CronParser parser = new CronParser(cronDefinition);
ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("* * * * * * *"));
DateTime nextExecution = executionTime.nextExecution(now));
According to the official description, cron-utils is:
A Java library to parse, validate, migrate crons as well as get human readable descriptions for them. The project follows the Semantic Versioning Convention and uses Apache 2.0 license.

João Neves
- 944
- 1
- 13
- 18