How to get the next LocalDateTime from an initial LocalDateTime and a cron expression?

Viewed 2246

I have an initial date and a cron expression. How could I find the next date satisfying this cron expression ?.

    String cronExpresion = "* * * * * *"
    LocalDateTime initial = LocalDateTime.now()
    LocalDateTime next = ?

I tried CronSequenceGenerator and its next() method but it uses java.util.Date and I would prefer not to convert LocalDateTime to Date and vice versa. Plus, I've got different result (time between the 2 dates) from several run with a cron like 'every 10 secondes' ...

Any idea ? lib ?

3 Answers

Another solution is to use CronSequenceGenerator from spring.

String cronExpresion = "* * * * * *";
Date next = new CronSequenceGenerator().next(new Date());
return LocalDateTime.ofInstant(next.toInstant(), ZoneId.systemDefault());

Finally Spring with version 5.3.0 published new version of CronExpression which is not connected to old java time API

Related