3

I am trying to convert the cron expression to date. for example this is 0 0 23 1 1-12 ? expression. I want to convert to corresponding date. How do I achieve this?

This is what I tried but it just give the description, Human readable but I want to achieve proper date format.

import java.text.ParseException;
import java.util.Date;

import org.quartz.CronExpression;

public class CRON {
 
 public static void main(String args[]) throws ParseException
 {
  //AutoRegistrationJobDao obj=new AutoRegistrationJobDao();
  //obj.updateLastAutoRegSchdl();
  
  String cron ="0 0 23 1 1-12 ?";
  System.out.println("cron :"+cron);
  
  CronExpression cronExpression =new CronExpression("0 0 23 1 1-12 ?");
  System.out.println(cronExpression.getExpressionSummary());
  System.out.println(cronExpression.getFinalFireTime());
  //System.out.println(cronExpression.getNextValidTimeAfter(date));
  
  try {
   CronExpression c =new CronExpression(cron);
   Date date=c.getFinalFireTime();
   System.out.println(date);
   
   
   System.out.println(c.getFinalFireTime());
   
   
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }
   
}
This is what I tried, I am using multiple method and using different class, but no luck Output:
seconds: 0
minutes: 0
hours: 23
daysOfMonth: 1
months: 1,2,3,4,5,6,7,8,9,10,11,12
daysOfWeek: ?
lastdayOfWeek: false
nearestWeekday: false
NthDayOfWeek: 0
lastdayOfMonth: false
Varun
  • 4,342
  • 19
  • 84
  • 119

3 Answers3

1

Please check if this one works!!!

import org.springframework.scheduling.support.CronSequenceGenerator;
import java.util.Date;

CronSequenceGenerator generator = new CronSequenceGenerator("0 0 23 * * ?");
Date nextRunDate= generator.next(new Date());
System.out.println("Date:: " + nextRunDate);
mule-user
  • 223
  • 5
  • 22
0

*/20 * * * * command -> this will execute once in 20 min. This cannot be mapped to a single point of time.

Given a cron expression - there will be multplie instance in time when the job should get triggered. So you cannot expect a one to one mapping b/w the cron and a date instance.

If you have a date reference, you can figure out the next job trigger time or the like from the reference date.

Balaji Krishnan
  • 1,007
  • 3
  • 12
  • 29
0

The Spring CronSequenceGenerator is deprecated.

You can use CronExpression instead.
Official Spring Documentation.

import org.springframework.scheduling.support.CronExpression;
import java.time.LocalDateTime;

CronExpression cronExpression = CronExpression.parse("0 0 23 * * ?");
LocalDateTime nextRunDate = cronExpression.next(LocalDateTime.now()); //Nullable
Diazed
  • 66
  • 4