How to generate a CRON Expression from a Date Object

Posted: April 1, 2014 in General, Java, Uncategorized

Today we are gonna see a custom utility class that converts a date object to a cron expression

public class CronUtil {

private final Date mDate;
private final Calendar mCal;
private final String mSeconds = “0”;
private final String mDaysOfWeek = “?”;

private String mMins;
private String mHours;
private String mDaysOfMonth;
private String mMonths;
private String mYears;

public CronUtil(Date pDate) {
this.mDate = pDate;
mCal = Calendar.getInstance();
this.generateCronExpression();
}

private void generateCronExpression() {
mCal.setTime(mDate);

String hours = String.valueOf(mCal.get(Calendar.HOUR_OF_DAY));
this.mHours = hours;

String mins = String.valueOf(mCal.get(Calendar.MINUTE));
this.mMins = mins;

String days = String.valueOf(mCal.get(Calendar.DAY_OF_MONTH));
this.mDaysOfMonth = days;

String months = new java.text.SimpleDateFormat(“MM”).format(mCal.getTime());
this.mMonths = months;

String years = String.valueOf(mCal.get(Calendar.YEAR));
this.mYears = years;

}

public Date getDate() {
return mDate;
}

public String getSeconds() {
return mSeconds;
}

public String getMins() {
return mMins;
}

public String getDaysOfWeek() {
return mDaysOfWeek;
}

public String getHours() {
return mHours;
}

public String getDaysOfMonth() {
return mDaysOfMonth;
}

public String getMonths() {
return mMonths;
}

public String getYears() {
return mYears;
}

}

 

Now lets see how to use this class

 

public void generateCronExpression(Date date) {

try {

SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
String dt = dateFormat.format(date);

Date cronDate = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”).parse(dt);

CronUtil calHelper = new CronUtil (cronDate);
String cron = calHelper.getSecondsDuration() + ” ” +
calHelper.getMinsDuration() + ” ” +
calHelper.getHoursDuration() + ” ” +
calHelper.getDaysOfMonthDuration() + ” ” +
calHelper.getMonthsDuration() + ” ” +
calHelper.getDaysOfWeekDuration() + ” ” +
calHelper.getYearsDuration();
logger.debug(“Cron Expression ” + cron);

}

Advertisements
Comments
  1. tolga says:

    CronUtility class is not defined a copy paster error maybe.

  2. Kirti says:

    Please share cronUtility.

  3. Kirti says:

    Got it
    CronUtil class is a CroneUtility

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s